安全与效率优化,引入Redis,包名修改

This commit is contained in:
lxp
2026-10-22 14:01:10 +08:00
parent cdc1e4d261
commit 961a61afb4
231 changed files with 5782 additions and 2049 deletions
@@ -0,0 +1,8 @@
package com.linkerbot.vibemake.service;
import com.linkerbot.vibemake.bean.ai.AiContracts.ChatRequest;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
public interface AiSearchService {
SseEmitter chat(long userId, ChatRequest request);
}
@@ -0,0 +1,9 @@
package com.linkerbot.vibemake.service;
import com.linkerbot.vibemake.bean.Contracts.CoverUploadInput;
import com.linkerbot.vibemake.bean.Contracts.CoverUploadSignature;
/** 为浏览器直传项目封面生成 OSS POST 表单,不接收图片内容。 */
public interface CoverUploadService {
CoverUploadSignature signature(long userId, CoverUploadInput input);
}
@@ -0,0 +1,41 @@
package com.linkerbot.vibemake.service;
import com.linkerbot.vibemake.bean.Contracts.CommitInput;
import com.linkerbot.vibemake.bean.Contracts.CommitView;
import com.linkerbot.vibemake.bean.Contracts.FileView;
import com.linkerbot.vibemake.bean.Contracts.HistoryEntry;
import com.linkerbot.vibemake.bean.Contracts.TreeView;
import com.linkerbot.vibemake.common.PageResponse;
import com.linkerbot.vibemake.service.gitea.GiteaClient;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/** 工作区和社区的目录、文件、提交与历史查询。 */
public interface FileService {
TreeView ownerTree(long userId, String code, String path, String commitSha);
TreeView vibemakeTree(String code, String path);
GiteaClient.StoredFile ownerFile(long userId, String code, String path, String commitSha);
FileView ownerFileView(long userId, String code, String path, String commitSha);
GiteaClient.StoredFile vibemakeFile(String code, String path);
FileView vibemakeFileView(String code, String path);
CommitView commit(long userId, String code, CommitInput input);
CommitView upload(
long userId,
String code,
String expectedSha,
String message,
String directory,
List<MultipartFile> files,
List<String> paths);
PageResponse<HistoryEntry> history(long userId, String code, long page, long size);
}
@@ -0,0 +1,18 @@
package com.linkerbot.vibemake.service;
import com.linkerbot.vibemake.bean.Contracts.CommentInput;
import com.linkerbot.vibemake.bean.Contracts.CommentView;
import com.linkerbot.vibemake.common.PageResponse;
/** 社区评论和幂等点赞操作。 */
public interface InteractionService {
PageResponse<CommentView> list(String code, long page, long size);
CommentView comment(long userId, String code, CommentInput input);
void deleteComment(long userId, String code);
void like(long userId, String code);
void unlike(long userId, String code);
}
@@ -0,0 +1,48 @@
package com.linkerbot.vibemake.service;
import com.linkerbot.vibemake.bean.Contracts.ForkInput;
import com.linkerbot.vibemake.bean.Contracts.ProjectInput;
import com.linkerbot.vibemake.bean.Contracts.ProjectView;
import com.linkerbot.vibemake.bean.Contracts.TypeView;
import com.linkerbot.vibemake.bean.entity.Project;
import com.linkerbot.vibemake.common.PageResponse;
import com.linkerbot.vibemake.service.gitea.GiteaClient;
import java.util.List;
import java.util.function.Function;
/** 项目管理、社区发布以及文件和互动服务共用的项目访问能力。 */
public interface ProjectService {
List<TypeView> types();
ProjectView view(Project project, Long currentUser);
List<ProjectView> views(List<Project> records, Long currentUser);
PageResponse<ProjectView> list(
Long ownerId, String type, String keyword, long page, long size, Long currentUser);
ProjectView create(long userId, ProjectInput input);
ProjectView fork(long userId, String sourceCode, ForkInput input);
ProjectView update(long userId, String code, ProjectInput input);
void delete(long userId, String code);
ProjectView publish(long userId, String code, String expectedSha);
void withdraw(long userId, String code);
Project owner(long userId, String code);
Project readyOwner(long userId, String code);
void ready(Project project);
Project published(String code);
GiteaClient.Repository repository(Project project);
<T> T write(long userId, String code, Function<Project, T> action);
}
@@ -0,0 +1,14 @@
package com.linkerbot.vibemake.service;
import com.linkerbot.vibemake.bean.Contracts.ProjectView;
import com.linkerbot.vibemake.bean.Contracts.UrdfConfirmInput;
import com.linkerbot.vibemake.bean.Contracts.UrdfUploadInput;
import com.linkerbot.vibemake.bean.Contracts.UrdfUploadSignature;
public interface UrdfService {
UrdfUploadSignature signature(long userId, String projectCode, UrdfUploadInput input);
ProjectView confirm(long userId, String projectCode, UrdfConfirmInput input);
void clear(long userId, String projectCode);
}
@@ -0,0 +1,18 @@
package com.linkerbot.vibemake.service;
import com.linkerbot.vibemake.bean.Contracts.PublicUser;
import com.linkerbot.vibemake.bean.Contracts.UserView;
import com.linkerbot.vibemake.bean.entity.User;
/** 平台用户查询、登录和公开信息转换。 */
public interface UserService {
User login(String email);
User require(long id);
UserView view(User user);
PublicUser publicView(long id);
java.util.Map<Long, PublicUser> publicViews(java.util.Collection<Long> ids);
}
@@ -0,0 +1,770 @@
package com.linkerbot.vibemake.service.admin;
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.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.bean.AdminContracts.*;
import com.linkerbot.vibemake.bean.Contracts.UrdfConfirmInput;
import com.linkerbot.vibemake.bean.Contracts.UrdfUploadSignature;
import com.linkerbot.vibemake.bean.entity.*;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.service.config.*;
import com.linkerbot.vibemake.service.gitea.*;
import com.linkerbot.vibemake.service.mapper.*;
import com.linkerbot.vibemake.service.migration.*;
import com.linkerbot.vibemake.service.oss.OssResourcePaths;
import com.linkerbot.vibemake.service.oss.UrdfResources;
import com.linkerbot.vibemake.service.support.*;
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;
import java.io.IOException;
import java.util.*;
@Service
@RequiredArgsConstructor
public class AdminImportService {
private final com.linkerbot.vibemake.service.state.RateLimits rateLimits;
private static final Logger log = LoggerFactory.getLogger(AdminImportService.class);
private final AdminManagementService management;
private final GitHubSourceChecks sources;
private final ProjectMapper projects;
private final ProjectImportTaskMapper tasks;
private final UserMapper users;
private final GiteaClient gitea;
private final VibemakeProperties properties;
private final AdminProperties settings;
private final ProjectLocks locks;
private final OssResourcePaths paths;
private final UrdfResources urdfResources;
private final ObjectMapper json;
private final TransactionTemplate transactions;
public ImportPreview preview(String url) {
management.requireAdmin();
GitHubSourceChecks.Repository source = check(url);
Project existing = existing(source.id());
return new ImportPreview(
source.url(),
source.defaultBranch(),
source.name(),
source.description(),
source.license(),
existing == null ? null : existing.getProjectCode());
}
private GitHubSourceChecks.Repository check(String url) {
try {
GitHubSourceChecks.repositoryKey(url);
return sources.repository(url);
} catch (BusinessException error) {
throw error;
} catch (IllegalArgumentException error) {
throw BusinessException.badRequest("必须填写HTTPS公开GitHub仓库根地址");
} catch (Exception error) {
if (error instanceof InterruptedException) Thread.currentThread().interrupt();
log.warn(
"GitHub预检失败 code=GITHUB_UNAVAILABLE errorType={}",
error.getClass().getSimpleName());
throw new BusinessException(502, "GITHUB_UNAVAILABLE", "GitHub预检未完成,请稍后重试");
}
}
private Project existing(long sourceId) {
ProjectImportTask task =
tasks.selectOne(
new LambdaQueryWrapper<ProjectImportTask>()
.eq(ProjectImportTask::getSourceRepositoryId, sourceId));
String code = task == null ? ProjectCodes.github(sourceId) : task.getProjectCode();
return projects.selectOne(
new LambdaQueryWrapper<Project>().eq(Project::getProjectCode, code));
}
private void requireNewSource(long sourceId) {
Project found = existing(sourceId);
if (found != null)
throw new BusinessException(
409,
"DUPLICATE_SOURCE",
"该来源已存在项目,请检查现有项目",
Map.of("projectCode", found.getProjectCode()));
}
public UrdfUploadSignature urdfSignature(ImportUrdfUploadInput input) {
management.requireAdmin();
rateLimits.operation("urdf-sign", 0);
urdfResources.requireEnabled();
GitHubSourceChecks.Repository source = check(input.repositoryUrl());
requireNewSource(source.id());
String code = ProjectCodes.github(source.id());
UrdfUploadSignature signature = urdfResources.sign(code, input.files());
log.info(
"生成迁移项目 URDF 签名 userCode={} projectCode={} batchCode={} fileCount={}",
ProjectActors.admin().userCode(),
code,
signature.batchCode(),
input.files().size());
return signature;
}
private record PreparedUrdf(String prefix, String mainObjectKey, String manifest) {}
private PreparedUrdf prepareUrdf(String projectCode, UrdfConfirmInput input) {
if (input == null) return null;
// 项目编码由重新校验的 GitHub 稳定标识生成,不能借用其他项目的上传批次。
// OSS 核验在数据库事务及项目锁之外完成,不依赖尚未创建的 Git 仓库。
urdfResources.verify(projectCode, input.batchCode(), input.files());
String prefix = urdfResources.prefix(projectCode, input.batchCode());
String main = urdfResources.validate(prefix, input.files());
return new PreparedUrdf(prefix, prefix + main, urdfResources.manifest(input.files()));
}
public TaskView create(ImportInput input) {
management.requireAdmin();
rateLimits.operation("create", 0);
ProjectInputs.validate(input.project(), properties);
GitHubSourceChecks.Repository source = check(input.repositoryUrl());
String code = ProjectCodes.github(source.id());
requireNewSource(source.id());
PreparedUrdf urdf = prepareUrdf(code, input.urdf());
User owner = management.owner(input.ownerUserCode());
return locks.serial(
code,
() -> {
requireNewSource(source.id());
try {
return transactions.execute(
status -> {
Project project = new Project();
project.setProjectCode(code);
project.setOwnerUserId(owner.getId());
project.setName(input.project().name().trim());
project.setDescription(
input.project().description() == null
? ""
: input.project().description());
project.setCoverUrl(
paths.coverStorage(input.project().coverUrl()));
if (urdf != null) {
project.setUrdfPrefix(urdf.prefix());
project.setUrdfMainObjectKey(urdf.mainObjectKey());
project.setUrdfFiles(urdf.manifest());
}
project.setProjectType(input.project().projectType());
project.setGiteaOwner(properties.getGitea().getOwner());
project.setGiteaRepoName("p_" + code);
project.setRepoStatus("CREATING");
project.setPublishStatus("UNPUBLISHED");
project.setDeleted(false);
project.setCreatedAt(ProjectSupport.now());
project.setUpdatedAt(project.getCreatedAt());
projects.insert(project);
ProjectImportTask task = new ProjectImportTask();
task.setTaskCode(Codes.next());
task.setProjectCode(code);
task.setSourceRepositoryId(source.id());
task.setSourceRepositoryUrl(source.url());
task.setSourceDefaultBranch(source.defaultBranch());
task.setSourceLicense(source.license());
task.setOperatorUserCode(ProjectActors.admin().userCode());
task.setStatus("QUEUED");
task.setPhase("QUEUED");
task.setWarningsJson("[]");
task.setCreatedAt(ProjectSupport.now());
task.setUpdatedAt(task.getCreatedAt());
tasks.insert(task);
log.info(
"创建迁移任务 userCode={} taskCode={} projectCode={}",
task.getOperatorUserCode(),
task.getTaskCode(),
code);
if (urdf != null)
log.info(
"迁移项目绑定 URDF userCode={} taskCode={} projectCode={}"
+ " batchCode={} fileCount={}",
task.getOperatorUserCode(),
task.getTaskCode(),
code,
input.urdf().batchCode(),
input.urdf().files().size());
return view(task);
});
} catch (DuplicateKeyException duplicate) {
throw new BusinessException(
409,
"DUPLICATE_SOURCE",
"来源项目或编码已被占用,请刷新核对",
Map.of("projectCode", code));
}
});
}
public ProjectImportTask task(String code) {
management.requireAdmin();
ProjectImportTask task = find(code);
if (task == null) throw BusinessException.notFound();
return task;
}
private ProjectImportTask find(String code) {
return tasks.selectOne(
new LambdaQueryWrapper<ProjectImportTask>()
.eq(ProjectImportTask::getTaskCode, code));
}
public TaskView view(ProjectImportTask task) {
try {
boolean retry = canRetry(task);
List<String> warnings =
json.readValue(
task.getWarningsJson() == null ? "[]" : task.getWarningsJson(),
new TypeReference<List<String>>() {});
return new TaskView(
task.getTaskCode(),
task.getProjectCode(),
task.getStatus(),
task.getPhase(),
task.getErrorCode(),
retry,
retryMessage(task, retry),
warnings,
task.getCreatedAt(),
task.getStartedAt(),
task.getFinishedAt());
} catch (IOException error) {
throw new IllegalStateException("迁移任务告警数据无效");
}
}
public PageResponse<TaskView> list(long page, long size, String status, String projectCode) {
management.requireAdmin();
ProjectSupport.pageCheck(page, size);
Page<ProjectImportTask> result =
tasks.selectPage(
new Page<>(page, size),
new LambdaQueryWrapper<ProjectImportTask>()
.eq(status != null, ProjectImportTask::getStatus, status)
.eq(
projectCode != null,
ProjectImportTask::getProjectCode,
projectCode)
.orderByDesc(ProjectImportTask::getCreatedAt)
.orderByDesc(ProjectImportTask::getId));
return new PageResponse<>(
result.getRecords().stream().map(this::view).toList(),
page,
size,
result.getTotal());
}
public TaskView retry(String code) {
ProjectImportTask initial = task(code);
return locks.serial(
initial.getProjectCode(),
() -> {
ProjectImportTask task = task(code);
Project project =
projects.selectOne(
new LambdaQueryWrapper<Project>()
.eq(Project::getProjectCode, task.getProjectCode())
.eq(Project::getDeleted, false));
if (!retryableProject(project))
throw BusinessException.conflict("项目已就绪、发布过、下架或删除,不能重试迁移");
if (!canRetry(task)) throw BusinessException.conflict("当前任务无法安全重试,请核对仓库状态");
boolean recreate = recreateOnRetry(task);
if (recreate) {
// 持久化清理意图后交给后台处理,接口不等待远端删除或迁移。
task.setPhase("CLEANING");
} else if ("REVIEW".equals(task.getStatus())) {
if (task.getReceiptJson() == null)
throw BusinessException.conflict("迁移结果不明,需要运维核对,禁止重发");
if ("MIGRATED".equals(task.getPhase())) {
engine().verifyReceipt(
task.getSourceRepositoryUrl(),
project.getGiteaRepoName(),
receipt(task));
} else if (Set.of("NORMALIZING", "BRANCH_READY").contains(task.getPhase())
&& task.getTargetSha() != null) {
engine().verifyNormalized(
task.getSourceRepositoryUrl(),
task.getSourceDefaultBranch(),
project.getGiteaRepoName(),
receipt(task),
task.getTargetSha());
task.setPhase("BRANCH_READY");
} else throw BusinessException.conflict("迁移结果需要运维核对,禁止重发");
locks.confirmKnownResult(project.getProjectCode());
} else if (!"FAILED".equals(task.getStatus()))
throw BusinessException.conflict("仅失败或可核验的待核对任务允许续跑");
if (!"IDLE".equals(project.getRepoWriteStatus())
&& !"REVIEW".equals(task.getStatus())
&& !recreate) throw BusinessException.conflict("仓库写入状态需要人工核对");
tasks.update(
null,
new LambdaUpdateWrapper<ProjectImportTask>()
.eq(ProjectImportTask::getId, task.getId())
.set(ProjectImportTask::getStatus, "QUEUED")
.set(ProjectImportTask::getPhase, task.getPhase())
.set(ProjectImportTask::getErrorCode, null)
.set(ProjectImportTask::getFinishedAt, null)
.set(ProjectImportTask::getUpdatedAt, ProjectSupport.now()));
log.info(
"迁移重试已排队 operatorUserCode={} taskCode={} projectCode={} cleanup={}",
ProjectActors.admin().userCode(),
code,
task.getProjectCode(),
recreate);
return view(task(code));
});
}
private boolean recreateOnRetry(ProjectImportTask task) {
if (task.getReceiptJson() != null) return false;
if ("MIGRATING".equals(task.getPhase()))
return "GITEA_MIGRATION_REJECTED".equals(task.getErrorCode());
// 人工清理后仍使用原入口重新核验。是否可删除由后台的仓库归属检查决定,
// 不因错误码被清除或用户再次点击而绕过;来源身份已变化则继续阻断。
return "CLEANING".equals(task.getPhase()) && !"SOURCE_CHANGED".equals(task.getErrorCode());
}
private boolean canRetry(ProjectImportTask task) {
if (!Set.of("FAILED", "REVIEW").contains(task.getStatus())) return false;
Project project =
projects.selectOne(
new LambdaQueryWrapper<Project>()
.eq(Project::getProjectCode, task.getProjectCode()));
if (!retryableProject(project)) return false;
if (recreateOnRetry(task)) return true;
if ("CLEANING".equals(task.getPhase())) return false;
if ("FAILED".equals(task.getStatus())) return true;
return task.getReceiptJson() != null
&& ("MIGRATED".equals(task.getPhase())
|| Set.of("NORMALIZING", "BRANCH_READY").contains(task.getPhase())
&& task.getTargetSha() != null);
}
private boolean retryableProject(Project project) {
return project != null
&& !Boolean.TRUE.equals(project.getDeleted())
&& "UNPUBLISHED".equals(project.getPublishStatus())
&& Set.of("CREATING", "FAILED").contains(project.getRepoStatus())
&& project.getPublishedCommitSha() == null
&& project.getPublishedAt() == null;
}
private String retryMessage(ProjectImportTask task, boolean retry) {
if (!Set.of("FAILED", "REVIEW").contains(task.getStatus())) return null;
if (!retry) return "当前项目状态或远端结果不允许安全重试,需要维护人员核对";
if ("CLEANING".equals(task.getPhase())
&& Set.of("CLEANUP_REPOSITORY_UNSAFE", "CLEANUP_REPOSITORY_REPLACED")
.contains(task.getErrorCode() == null ? "" : task.getErrorCode()))
return "残留仓库身份核验未通过;若已手工删除目标仓库,可重试核验并继续迁移,保留项目资料、封面和 URDF";
if (recreateOnRetry(task)) return "将核验并清理本任务的失败仓库后重新迁移,保留项目资料、封面和 URDF";
if (task.getReceiptJson() != null) return "将核验已迁移的仓库并继续后续步骤,不会删除仓库";
return "将重新检查来源并继续迁移,保留项目资料、封面和 URDF";
}
private String migrationMarker(ProjectImportTask task) {
return "vibemake-import:" + task.getTaskCode();
}
private GiteaClient.RemoteRepository failedRepository(ProjectImportTask task, Project project) {
GiteaClient.MigrationTarget target;
try {
target = gitea.inspectMigrationTarget(project.getGiteaRepoName());
} catch (GiteaFailure missing) {
if (missing.status() == 404) return null;
throw missing;
}
GiteaClient.RemoteRepository remote = target.repository();
boolean sourceMatches;
try {
sourceMatches =
GitHubSourceChecks.repositoryKey(remote.originalUrl())
.equalsIgnoreCase(
GitHubSourceChecks.repositoryKey(
task.getSourceRepositoryUrl()));
} catch (RuntimeException error) {
sourceMatches = false;
}
if (!migrationMarker(task).equals(target.description())
|| !properties.getGitea().getOwner().equals(project.getGiteaOwner())
|| !project.getGiteaOwner().equals(remote.owner())
|| !project.getGiteaRepoName().equals(remote.name())
|| !remote.privateRepo()
|| remote.mirror()
|| !sourceMatches)
throw new MigrationFailure("CLEANUP_REPOSITORY_UNSAFE", "无法确认残留仓库属于本次失败迁移,未执行删除");
if (project.getGiteaRepoId() != null && project.getGiteaRepoId() != remote.id())
throw new MigrationFailure("CLEANUP_REPOSITORY_REPLACED", "目标仓库身份已变化,未执行删除");
return remote;
}
private void rememberFailedRepository(
ProjectImportTask task, Project project, GiteaClient.RemoteRepository remote) {
if (remote == null) return;
if (project.getGiteaRepoId() == null) {
int updated =
projects.update(
null,
new LambdaUpdateWrapper<Project>()
.eq(Project::getProjectCode, task.getProjectCode())
.eq(Project::getDeleted, false)
.in(Project::getRepoStatus, List.of("CREATING", "FAILED"))
.isNull(Project::getGiteaRepoId)
.set(Project::getGiteaRepoId, remote.id()));
if (updated != 1) throw BusinessException.conflict("项目状态已变化,停止清理");
project.setGiteaRepoId(remote.id());
}
}
private void cleanupFailedMigration(ProjectImportTask task, Project project) {
if (task.getReceiptJson() != null || !retryableProject(project))
throw new MigrationFailure("CLEANUP_REPOSITORY_UNSAFE", "项目已就绪或已有发布记录,禁止清理仓库");
GitHubSourceChecks.Repository source = check(task.getSourceRepositoryUrl());
if (source.id() != task.getSourceRepositoryId())
throw new MigrationFailure("SOURCE_CHANGED", "来源仓库身份已变化,停止清理");
phase(task, "CLEANING");
GiteaClient.RemoteRepository remote = failedRepository(task, project);
rememberFailedRepository(task, project, remote);
if (remote != null) {
log.info(
"清理失败迁移仓库 taskCode={} projectCode={}",
task.getTaskCode(),
task.getProjectCode());
gitea.deleteRepository(remote.repository());
}
// 删除响应成功也必须再次确认目标不存在;超时或回写失败可从 CLEANING 恢复。
engine().ensureAbsent(project.getGiteaRepoName());
transactions.executeWithoutResult(
status -> {
int updated =
projects.update(
null,
new LambdaUpdateWrapper<Project>()
.eq(Project::getProjectCode, task.getProjectCode())
.eq(Project::getDeleted, false)
.in(
Project::getRepoStatus,
List.of("CREATING", "FAILED"))
.eq(Project::getPublishStatus, "UNPUBLISHED")
.set(Project::getGiteaRepoId, null)
.set(Project::getRepoStatus, "CREATING")
.set(Project::getRepoWriteStatus, "IDLE"));
if (updated != 1) throw BusinessException.conflict("项目状态已变化,停止重新迁移");
task.setPhase("PRECHECK");
task.setTargetSha(null);
task.setErrorCode(null);
save(task);
});
locks.confirmKnownResult(task.getProjectCode());
log.info(
"失败迁移仓库清理已确认 taskCode={} projectCode={}",
task.getTaskCode(),
task.getProjectCode());
}
public List<String> queued() {
return tasks
.selectList(
new LambdaQueryWrapper<ProjectImportTask>()
.eq(ProjectImportTask::getStatus, "QUEUED")
.orderByAsc(ProjectImportTask::getCreatedAt)
.last("LIMIT " + settings.getImportConcurrency()))
.stream()
.map(ProjectImportTask::getTaskCode)
.toList();
}
public void recover() {
// 单实例管理端重启后,远端阶段一律待核对;只读预检阶段可以重新排队。
tasks.update(
null,
new LambdaUpdateWrapper<ProjectImportTask>()
.eq(ProjectImportTask::getStatus, "RUNNING")
.in(ProjectImportTask::getPhase, List.of("QUEUED", "PRECHECK"))
.set(ProjectImportTask::getStatus, "QUEUED")
.set(ProjectImportTask::getUpdatedAt, ProjectSupport.now()));
tasks.update(
null,
new LambdaUpdateWrapper<ProjectImportTask>()
.eq(ProjectImportTask::getStatus, "RUNNING")
.set(ProjectImportTask::getStatus, "REVIEW")
.set(ProjectImportTask::getErrorCode, "PROCESS_INTERRUPTED")
.set(ProjectImportTask::getFinishedAt, ProjectSupport.now())
.set(ProjectImportTask::getUpdatedAt, ProjectSupport.now()));
}
public void run(String code) {
int claimed =
tasks.update(
null,
new LambdaUpdateWrapper<ProjectImportTask>()
.eq(ProjectImportTask::getTaskCode, code)
.eq(ProjectImportTask::getStatus, "QUEUED")
.set(ProjectImportTask::getStatus, "RUNNING")
.set(ProjectImportTask::getStartedAt, ProjectSupport.now())
.set(ProjectImportTask::getUpdatedAt, ProjectSupport.now()));
if (claimed != 1) return;
ProjectImportTask task = find(code);
try {
locks.serial(
task.getProjectCode(),
() -> {
try {
process(task);
} catch (RuntimeException error) {
fail(code, error);
}
return null;
});
} catch (RuntimeException error) {
fail(code, error);
}
}
private void process(ProjectImportTask task) {
Project project =
projects.selectOne(
new LambdaQueryWrapper<Project>()
.eq(Project::getProjectCode, task.getProjectCode())
.eq(Project::getDeleted, false));
if (project == null
|| !"CREATING".equals(project.getRepoStatus())
&& !"FAILED".equals(project.getRepoStatus()))
throw BusinessException.conflict("项目状态已变化,停止迁移");
User operator =
users.selectOne(
new LambdaQueryWrapper<User>()
.eq(User::getUserCode, task.getOperatorUserCode()));
if (operator == null
|| !"ADMIN".equals(operator.getRole())
|| !"ACTIVE".equals(operator.getStatus()))
throw new BusinessException(403, "OPERATOR_UNAVAILABLE", "任务创建人已无后台权限");
if ("CLEANING".equals(task.getPhase())) cleanupFailedMigration(task, project);
try {
RepositoryMigration.Result result;
if ("BRANCH_READY".equals(task.getPhase()) && task.getReceiptJson() != null) {
result =
engine().verifyNormalized(
task.getSourceRepositoryUrl(),
task.getSourceDefaultBranch(),
project.getGiteaRepoName(),
receipt(task),
task.getTargetSha());
} else {
if (task.getReceiptJson() == null) {
phase(task, "PRECHECK");
GitHubSourceChecks.Repository source = check(task.getSourceRepositoryUrl());
if (source.id() != task.getSourceRepositoryId())
throw new MigrationFailure("SOURCE_CHANGED", "来源仓库标识已变化");
gitea.checkMigrationSettings();
}
result =
engine().run(
task.getSourceRepositoryUrl(),
task.getSourceRepositoryUrl(),
task.getSourceDefaultBranch(),
project.getGiteaRepoName(),
settings.getMigrationTimeout(),
new RepositoryMigration.Progress() {
public GiteaClient.RemoteRepository receipt() {
return AdminImportService.this.receipt(task);
}
public String targetSha() {
return task.getTargetSha();
}
public String migrationDescription() {
return migrationMarker(task);
}
public void receipt(
GiteaClient.RemoteRepository receipt)
throws IOException {
String data = json.writeValueAsString(receipt);
tasks.update(
null,
new LambdaUpdateWrapper<ProjectImportTask>()
.eq(
ProjectImportTask::getId,
task.getId())
.set(
ProjectImportTask
::getReceiptJson,
data)
.set(
ProjectImportTask::getPhase,
"MIGRATED")
.set(
ProjectImportTask
::getUpdatedAt,
ProjectSupport.now()));
task.setReceiptJson(data);
task.setPhase("MIGRATED");
}
public void targetSha(String sha) {
task.setTargetSha(sha);
save(task);
}
public void phase(String next) {
AdminImportService.this.phase(task, next);
}
});
}
List<String> warnings;
try {
warnings =
gitea.migrationWarnings(
result.remote().repository(),
result.sha(),
properties.getMaxFileBytes());
} catch (RuntimeException error) {
warnings = List.of("兼容性扫描未完成,请检查大文件、LFS、子模块及符号链接");
}
String warningsJson = json.writeValueAsString(warnings);
transactions.executeWithoutResult(
status -> {
int updated =
projects.update(
null,
new LambdaUpdateWrapper<Project>()
.eq(Project::getProjectCode, task.getProjectCode())
.eq(Project::getDeleted, false)
.set(Project::getGiteaRepoId, result.remote().id())
.set(Project::getRepoStatus, "READY")
.set(Project::getRepoWriteStatus, "IDLE")
.set(Project::getUpdatedAt, ProjectSupport.now()));
if (updated != 1) throw BusinessException.conflict("项目已变化,不能关联迁移结果");
tasks.update(
null,
new LambdaUpdateWrapper<ProjectImportTask>()
.eq(ProjectImportTask::getId, task.getId())
.set(ProjectImportTask::getStatus, "SUCCEEDED")
.set(ProjectImportTask::getPhase, "LINKED")
.set(ProjectImportTask::getWarningsJson, warningsJson)
.set(ProjectImportTask::getErrorCode, null)
.set(ProjectImportTask::getFinishedAt, ProjectSupport.now())
.set(
ProjectImportTask::getUpdatedAt,
ProjectSupport.now()));
});
log.info(
"后台迁移完成 userCode={} taskCode={} projectCode={} commitSha={}",
task.getOperatorUserCode(),
task.getTaskCode(),
task.getProjectCode(),
result.sha());
} catch (IOException error) {
throw new IllegalStateException("迁移收据持久化未确认", error);
}
}
private void fail(String code, RuntimeException error) {
boolean interrupted = Thread.interrupted();
try {
ProjectImportTask task = find(code);
boolean review =
Set.of("CLEANING", "MIGRATING", "MIGRATED", "NORMALIZING", "BRANCH_READY")
.contains(task.getPhase());
if (error instanceof GiteaFailure failure && failure.uncertain()) review = true;
if (error instanceof MigrationFailure failure
&& "REMOTE_ALREADY_EXISTS".equals(failure.code())) review = true;
boolean rejected =
"MIGRATING".equals(task.getPhase())
&& task.getReceiptJson() == null
&& error instanceof GiteaFailure failure
&& "GITEA_MIGRATION_REJECTED".equals(failure.code())
&& !failure.uncertain();
if (rejected) {
review = false;
try {
Project project =
projects.selectOne(
new LambdaQueryWrapper<Project>()
.eq(Project::getProjectCode, task.getProjectCode()));
if (project != null)
rememberFailedRepository(task, project, failedRepository(task, project));
} catch (RuntimeException inspectError) {
log.warn(
"失败迁移仓库身份未记录 taskCode={} projectCode={} errorType={}",
code,
task.getProjectCode(),
inspectError.getClass().getSimpleName());
}
}
String errorCode =
error instanceof BusinessException business
? business.code()
: "IMPORT_INTERNAL_ERROR";
if (review || rejected) locks.markUncertain(task.getProjectCode());
tasks.update(
null,
new LambdaUpdateWrapper<ProjectImportTask>()
.eq(ProjectImportTask::getId, task.getId())
.set(ProjectImportTask::getStatus, review ? "REVIEW" : "FAILED")
.set(ProjectImportTask::getErrorCode, errorCode)
.set(ProjectImportTask::getFinishedAt, ProjectSupport.now())
.set(ProjectImportTask::getUpdatedAt, ProjectSupport.now()));
log.error(
"后台迁移失败 userCode={} taskCode={} projectCode={} phase={} code={} review={}"
+ " errorType={}",
task.getOperatorUserCode(),
code,
task.getProjectCode(),
task.getPhase(),
errorCode,
review,
error.getClass().getSimpleName());
} finally {
if (interrupted) Thread.currentThread().interrupt();
}
}
private void phase(ProjectImportTask task, String phase) {
transactions.executeWithoutResult(
status -> {
task.setPhase(phase);
save(task);
if (Set.of("CLEANING", "MIGRATING", "NORMALIZING").contains(phase)) {
int updated =
projects.update(
null,
new LambdaUpdateWrapper<Project>()
.eq(Project::getProjectCode, task.getProjectCode())
.eq(Project::getDeleted, false)
.set(Project::getRepoWriteStatus, "WRITING"));
if (updated != 1) throw BusinessException.conflict("项目状态已变化,停止迁移");
}
});
}
private void save(ProjectImportTask task) {
task.setUpdatedAt(ProjectSupport.now());
if (tasks.updateById(task) != 1) throw new IllegalStateException("迁移进度保存失败");
}
private GiteaClient.RemoteRepository receipt(ProjectImportTask task) {
if (task.getReceiptJson() == null) return null;
try {
return json.readValue(task.getReceiptJson(), GiteaClient.RemoteRepository.class);
} catch (IOException error) {
throw new IllegalStateException("迁移收据无效");
}
}
private RepositoryMigration engine() {
return new RepositoryMigration(gitea, properties.getGitea().getOwner());
}
}
@@ -0,0 +1,277 @@
package com.linkerbot.vibemake.service.admin;
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.AdminContracts;
import com.linkerbot.vibemake.bean.Contracts;
import com.linkerbot.vibemake.bean.entity.*;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.service.ProjectService;
import com.linkerbot.vibemake.service.mapper.*;
import com.linkerbot.vibemake.service.support.*;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class AdminManagementService {
private static final Logger log = LoggerFactory.getLogger(AdminManagementService.class);
private final UserMapper users;
private final ProjectMapper mapper;
private final ProjectService projects;
private final ProjectLocks locks;
public void requireAdmin() {
if (!ProjectActors.isAdmin()) throw new BusinessException(403, "FORBIDDEN", "此操作仅限后台管理员");
}
public User user(String code) {
requireAdmin();
User user = users.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserCode, code));
if (user == null) throw BusinessException.notFound();
return user;
}
public AdminContracts.UserView userView(User user) {
requireAdmin();
long count =
mapper.selectCount(
new LambdaQueryWrapper<Project>()
.eq(Project::getOwnerUserId, user.getId())
.eq(Project::getDeleted, false));
return new AdminContracts.UserView(
user.getUserCode(),
user.getNickname(),
user.getEmail(),
user.getStatus(),
user.getRole(),
count,
user.getCreatedAt());
}
public PageResponse<AdminContracts.UserView> users(
long page,
long size,
String userCode,
String nickname,
String email,
String role,
String status) {
requireAdmin();
ProjectSupport.pageCheck(page, size);
checkKeyword(nickname);
checkKeyword(email);
if (role != null && !Set.of("USER", "ADMIN", "OFFICIAL").contains(role))
throw BusinessException.badRequest("角色不合法");
if (status != null && !Set.of("ACTIVE", "DISABLED").contains(status))
throw BusinessException.badRequest("状态不合法");
LambdaQueryWrapper<User> query =
new LambdaQueryWrapper<User>()
.eq(userCode != null, User::getUserCode, userCode)
.like(nickname != null, User::getNickname, nickname)
.like(email != null, User::getEmail, email)
.eq(role != null, User::getRole, role)
.eq(status != null, User::getStatus, status)
.orderByDesc(User::getCreatedAt)
.orderByDesc(User::getId);
Page<User> result = users.selectPage(new Page<>(page, size), query);
Map<Long, Long> counts = new HashMap<>();
if (!result.getRecords().isEmpty())
for (EntityCount count :
mapper.ownerCounts(result.getRecords().stream().map(User::getId).toList()))
counts.put(count.entityId(), count.total());
return new PageResponse<>(
result.getRecords().stream()
.map(
user ->
new AdminContracts.UserView(
user.getUserCode(),
user.getNickname(),
user.getEmail(),
user.getStatus(),
user.getRole(),
counts.getOrDefault(user.getId(), 0L),
user.getCreatedAt()))
.toList(),
page,
size,
result.getTotal());
}
public AdminContracts.UserView nickname(String code, String nickname) {
User user = user(code);
users.update(
null,
new LambdaUpdateWrapper<User>()
.eq(User::getId, user.getId())
.set(User::getNickname, nickname.trim())
.set(User::getUpdatedAt, ProjectSupport.now()));
return userView(user(code));
}
public void status(String code, String status) {
User user = user(code);
if ("DISABLED".equals(status)
&& (code.equals(ProjectActors.admin().userCode())
|| "OFFICIAL".equals(user.getRole())))
throw BusinessException.conflict("不能禁用当前管理员或官方托管账号");
if (status.equals(user.getStatus())) return;
int updated =
users.update(
null,
new LambdaUpdateWrapper<User>()
.eq(User::getId, user.getId())
.eq(User::getStatus, user.getStatus())
.eq(User::getSessionVersion, user.getSessionVersion())
.set(User::getStatus, status)
.setSql("session_version = session_version + 1")
.set(User::getUpdatedAt, ProjectSupport.now()));
if (updated != 1) throw BusinessException.conflict("用户状态已变化,请刷新重试");
log.info(
"用户状态修改 operatorUserCode={} userCode={} status={}",
ProjectActors.admin().userCode(),
code,
status);
}
public User owner(String code) {
requireAdmin();
if (code != null && !code.isBlank()) {
User user = user(code);
if (!"ACTIVE".equals(user.getStatus()) || !"USER".equals(user.getRole()))
throw BusinessException.badRequest("只能指定正常普通用户为所有者");
return user;
}
User official =
users.selectOne(
new LambdaQueryWrapper<User>().eq(User::getEmail, OfficialUsers.EMAIL));
if (official == null) {
official = new User();
official.setUserCode(UserCodes.next());
official.setEmail(OfficialUsers.EMAIL);
official.setNickname("社区官方");
official.setStatus("ACTIVE");
official.setRole("OFFICIAL");
official.setCreatedAt(ProjectSupport.now());
official.setUpdatedAt(official.getCreatedAt());
try {
users.insert(official);
} catch (DuplicateKeyException duplicate) {
official =
users.selectOne(
new LambdaQueryWrapper<User>()
.eq(User::getEmail, OfficialUsers.EMAIL));
}
}
if (official == null
|| !"OFFICIAL".equals(official.getRole())
|| !"ACTIVE".equals(official.getStatus()))
throw BusinessException.conflict("官方托管账号状态异常,请人工核对");
return official;
}
public PageResponse<AdminContracts.ManagedProjectView> projects(
long page,
long size,
String ownerCode,
String type,
String keyword,
String publishStatus,
String repoStatus,
String moderationStatus) {
requireAdmin();
ProjectSupport.pageCheck(page, size);
checkKeyword(keyword);
LambdaQueryWrapper<Project> query =
new LambdaQueryWrapper<Project>().eq(Project::getDeleted, false);
query.select(Project.class, field -> !"urdfFiles".equals(field.getProperty()));
if (ownerCode != null) query.eq(Project::getOwnerUserId, user(ownerCode).getId());
query.eq(type != null, Project::getProjectType, type)
.eq(publishStatus != null, Project::getPublishStatus, publishStatus)
.eq(repoStatus != null, Project::getRepoStatus, repoStatus);
if (moderationStatus != null) {
if (!Set.of("NORMAL", "BLOCKED").contains(moderationStatus))
throw BusinessException.badRequest("治理状态不合法");
if ("BLOCKED".equals(moderationStatus)) query.eq(Project::getPublishStatus, "BLOCKED");
else query.ne(Project::getPublishStatus, "BLOCKED");
}
if (keyword != null && !keyword.isBlank())
query.and(
q ->
q.like(Project::getName, keyword)
.or()
.like(Project::getDescription, keyword));
query.orderByDesc(Project::getCreatedAt).orderByDesc(Project::getId);
Page<Project> result = mapper.selectPage(new Page<>(page, size), query);
List<Contracts.ProjectView> views = projects.views(result.getRecords(), null);
List<AdminContracts.ManagedProjectView> managed = new java.util.ArrayList<>();
for (int index = 0; index < views.size(); index++) {
Project project = result.getRecords().get(index);
managed.add(
new AdminContracts.ManagedProjectView(
views.get(index),
"BLOCKED".equals(project.getPublishStatus()) ? "BLOCKED" : "NORMAL",
project.getModerationReason(),
Boolean.TRUE.equals(project.getDeleted())));
}
return new PageResponse<>(List.copyOf(managed), page, size, result.getTotal());
}
public AdminContracts.ManagedProjectView projectView(Project project) {
requireAdmin();
return new AdminContracts.ManagedProjectView(
projects.view(project, null),
"BLOCKED".equals(project.getPublishStatus()) ? "BLOCKED" : "NORMAL",
project.getModerationReason(),
Boolean.TRUE.equals(project.getDeleted()));
}
public AdminContracts.ManagedProjectView detail(String code) {
requireAdmin();
return projectView(projects.owner(0, code));
}
public Contracts.ProjectView create(AdminContracts.CreateProjectInput input) {
User owner = owner(input.ownerUserCode());
return projects.create(owner.getId(), input.project());
}
public void moderate(String code, boolean blocked, String reason) {
requireAdmin();
locks.serial(
code,
() -> {
Project project = projects.owner(0, code);
LambdaUpdateWrapper<Project> update =
new LambdaUpdateWrapper<Project>()
.eq(Project::getId, project.getId())
.set(Project::getModerationReason, blocked ? reason : null)
.set(Project::getUpdatedAt, ProjectSupport.now());
if (blocked) update.set(Project::getPublishStatus, "BLOCKED");
else if ("BLOCKED".equals(project.getPublishStatus()))
update.set(Project::getPublishStatus, "UNPUBLISHED");
mapper.update(null, update);
log.info(
"项目治理 operatorUserCode={} projectCode={} blocked={}",
ProjectActors.admin().userCode(),
code,
blocked);
return null;
});
}
private void checkKeyword(String value) {
if (value != null && value.length() > 254) throw BusinessException.badRequest("查询条件过长");
}
}
@@ -0,0 +1,8 @@
package com.linkerbot.vibemake.service.ai;
import com.fasterxml.jackson.databind.JsonNode;
/** 可替换的模型边界,普通测试不调用真实方舟。 */
public interface AiModelClient {
JsonNode complete(String schemaName, JsonNode schema, String systemPrompt, JsonNode input);
}
@@ -0,0 +1,182 @@
package com.linkerbot.vibemake.service.ai;
import static com.linkerbot.vibemake.service.ai.AiResponseValidation.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.linkerbot.vibemake.bean.Contracts.ForkInput;
import com.linkerbot.vibemake.bean.Contracts.ProjectInput;
import com.linkerbot.vibemake.bean.Contracts.ProjectView;
import com.linkerbot.vibemake.bean.ai.AiContracts.*;
import com.linkerbot.vibemake.bean.entity.Project;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.ProjectService;
import com.linkerbot.vibemake.service.ai.AiProjectSearch.Criteria;
import com.linkerbot.vibemake.service.config.VibemakeProperties;
import com.linkerbot.vibemake.service.support.ProjectInputs;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/** 模型生成聊天回复或解析项目参数;项目访问、操作选择和实际写入由后端完成。 */
@Component
@RequiredArgsConstructor
public class AiProjectAssistant {
private static final Logger log = LoggerFactory.getLogger(AiProjectAssistant.class);
private final ObjectMapper json;
private final AiModelClient model;
private final AiSearchRules rules;
private final VibemakeProperties properties;
private final AiProjectSearch search;
private final ProjectService projects;
public ChatResult chat(long userId, ChatRequest request, Consumer<Progress> progress) {
long started = System.nanoTime();
checkCancelled();
progress.accept(new Progress("understanding", "正在理解需求"));
Map<String, Project> previous = new HashMap<>();
search.visible(request.previousProjectCodes()).forEach(project -> previous.put(project.getProjectCode(), project));
ObjectNode input = json.createObjectNode().put("message", request.message());
input.set("history", json.valueToTree(request.history()));
input.set("allowedTypes", json.valueToTree(properties.getTypes()));
ArrayNode previousInput = input.putArray("previousProjects");
for (int index = 0; index < request.previousProjectCodes().size(); index++) {
Project project = previous.get(request.previousProjectCodes().get(index));
if (project != null) previousInput.add(search.snapshot(project).put("position", index + 1));
}
JsonNode raw = model.complete("vibemake_project_intent", rules.intentSchema(), rules.intentPrompt(), input);
checkCancelled();
Intent intent = intent(raw, previous.keySet(), request);
log.info("Maker AI 意图解析完成 action={} clarification={} durationMs={}",
intent.action(), !intent.clarification().isEmpty(), elapsed(started));
if (!intent.clarification().isEmpty()) return clarification(intent.clarification());
return switch (intent.action()) {
case CHAT -> new ChatResult(Status.CHAT, intent.reply(), List.of());
case SEARCH -> search.search(userId, intent.criteria(), false, progress);
case CREATE -> create(userId, intent, progress);
case FORK -> fork(userId, intent, progress);
};
}
private Intent intent(JsonNode node, Set<String> previousCodes, ChatRequest request) {
fields(node, "action", "projectType", "keywords", "requirements", "preferences", "focusProjectCodes",
"clarification", "projectName", "description", "coverUrl", "sourceProjectCode", "reply");
Action action;
try {
action = Action.valueOf(text(node.get("action"), 16, false));
} catch (IllegalArgumentException error) {
throw invalid("unknown_action");
}
String type = nullableText(node.get("projectType"), 64, false);
if (type != null && !properties.getTypes().containsKey(type)) throw invalid("unknown_type");
List<String> focus = strings(node.get("focusProjectCodes"), 5, 32);
if (!previousCodes.containsAll(focus)) throw invalid("unknown_focus");
Criteria criteria = new Criteria(type, strings(node.get("keywords"), 8, 100),
strings(node.get("requirements"), 5, 200), strings(node.get("preferences"), 5, 200), focus);
String name = nullableText(node.get("projectName"), 100, false);
String description = nullableText(node.get("description"), 2000, true);
String cover = nullableText(node.get("coverUrl"), 2048, true);
String sourceCode = nullableText(node.get("sourceProjectCode"), 32, false);
String clarification = text(node.get("clarification"), 200, true);
String reply = text(node.get("reply"), 2000, true);
if (action == Action.CHAT && reply.isBlank()) throw invalid("empty_chat_reply");
if (action != Action.CHAT && !node.get("reply").textValue().isEmpty()) throw invalid("unexpected_reply");
if (sourceCode != null && !request.previousProjectCodes().contains(sourceCode)
&& !providedByUser(request, sourceCode)) throw invalid("unprovided_source_project");
boolean conflicting = switch (action) {
case CHAT -> type != null || !criteria.keywords().isEmpty() || !criteria.requirements().isEmpty()
|| !criteria.preferences().isEmpty() || !focus.isEmpty() || name != null || description != null
|| cover != null || sourceCode != null || !node.get("clarification").textValue().isEmpty();
case SEARCH -> name != null || description != null || cover != null || sourceCode != null;
case CREATE -> sourceCode != null || !criteria.keywords().isEmpty()
|| !criteria.requirements().isEmpty() || !criteria.preferences().isEmpty() || !focus.isEmpty();
case FORK -> description != null || cover != null;
};
if (conflicting && (action == Action.CHAT || clarification.isEmpty()))
throw invalid("conflicting_action_parameters");
return new Intent(action, criteria, clarification, name, description, cover, sourceCode, reply);
}
private boolean providedByUser(ChatRequest request, String code) {
Pattern token = Pattern.compile("(?<![a-zA-Z0-9])" + Pattern.quote(code) + "(?![a-zA-Z0-9])");
if (token.matcher(request.message()).find()) return true;
return request.history().stream().filter(message -> "user".equals(message.role()))
.anyMatch(message -> token.matcher(message.content()).find());
}
private ChatResult create(long userId, Intent intent, Consumer<Progress> progress) {
if (intent.name() == null) return clarification("请描述你想创建的项目,例如用途、名称或机器人类型。");
String type = intent.criteria().projectType() == null ? "GENERAL" : intent.criteria().projectType();
if (!properties.getTypes().containsKey(type)) return clarification("请指定一个可用的项目类型。");
ProjectInput input = new ProjectInput(intent.name(), intent.description(), type, intent.coverUrl());
ProjectInputs.validate(input, properties);
progress.accept(new Progress("creating", "正在创建项目和初始化仓库"));
checkCancelled();
long started = System.nanoTime();
log.info("Maker AI 项目操作开始 action=CREATE");
try {
ProjectView project = projects.create(userId, input);
log.info("Maker AI 项目操作完成 action=CREATE projectCode={} durationMs={}", project.projectCode(), elapsed(started));
return new ChatResult(Status.CREATED, "已创建项目「" + project.name() + "」,可以进入工作区继续编辑。", List.of(), project);
} catch (BusinessException error) {
log.warn("Maker AI 项目操作失败 action=CREATE code={} durationMs={}", error.code(), elapsed(started));
throw error;
}
}
private ChatResult fork(long userId, Intent intent, Consumer<Progress> progress) {
String sourceCode = intent.sourceCode();
if (sourceCode == null) {
ChatResult found = search.search(userId, intent.criteria(), true, progress);
if (found.status() != Status.MATCHED) return found;
if (found.projects().size() > 1)
return new ChatResult(Status.NEEDS_SELECTION,
"找到多个匹配项目,请选择要 Fork 的项目,例如“Fork 第二个”;也可以同时指定副本名称。", found.projects());
sourceCode = found.projects().getFirst().project().projectCode();
}
checkCancelled();
Project source = projects.published(sourceCode);
String name = intent.name() == null ? source.getName() : intent.name();
// 来源的名称可能被其他调用方更新,执行前仍需按现有输入约束校验。
ProjectInputs.validateMetadata(new ProjectInput(name, source.getDescription(), source.getProjectType(), null), properties);
ForkInput input = new ForkInput(source.getPublishedCommitSha(), name);
progress.accept(new Progress("forking", "正在 Fork 项目到你的工作区"));
checkCancelled();
long started = System.nanoTime();
log.info("Maker AI 项目操作开始 action=FORK sourceProjectCode={}", sourceCode);
try {
ProjectView project = projects.fork(userId, sourceCode, input);
log.info("Maker AI 项目操作完成 action=FORK projectCode={} sourceProjectCode={} durationMs={}",
project.projectCode(), sourceCode, elapsed(started));
return new ChatResult(Status.FORKED, "已 Fork 为项目「" + project.name() + "」,可以进入工作区继续编辑。", List.of(), project);
} catch (BusinessException error) {
log.warn("Maker AI 项目操作失败 action=FORK sourceProjectCode={} code={} durationMs={}", sourceCode, error.code(), elapsed(started));
throw error;
}
}
private ChatResult clarification(String reply) {
return new ChatResult(Status.NEEDS_CLARIFICATION, reply, List.of());
}
private void checkCancelled() {
if (Thread.currentThread().isInterrupted())
throw new BusinessException(499, "AI_CANCELLED", "Maker AI 已取消");
}
private long elapsed(long started) { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started); }
private enum Action { CHAT, SEARCH, CREATE, FORK }
private record Intent(Action action, Criteria criteria, String clarification, String name,
String description, String coverUrl, String sourceCode, String reply) {}
}
@@ -0,0 +1,218 @@
package com.linkerbot.vibemake.service.ai;
import static com.linkerbot.vibemake.service.ai.AiResponseValidation.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.linkerbot.vibemake.bean.ai.AiContracts.*;
import com.linkerbot.vibemake.bean.entity.Project;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.ProjectService;
import com.linkerbot.vibemake.service.mapper.AiProjectMapper;
import com.linkerbot.vibemake.service.mapper.ProjectMapper;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.function.Consumer;
/** 同步检索流水线,数据可见性和引用校验均由后端控制。 */
@Component
@RequiredArgsConstructor
public class AiProjectSearch {
private static final Logger log = LoggerFactory.getLogger(AiProjectSearch.class);
private final ObjectMapper json;
private final AiModelClient model;
private final AiSearchRules rules;
private final ProjectMapper projects;
private final AiProjectMapper candidates;
private final ProjectService projectService;
public record Criteria(
String projectType,
List<String> keywords,
List<String> requirements,
List<String> preferences,
List<String> focusProjectCodes) {}
public ChatResult search(
long userId, Criteria intent, boolean forFork, Consumer<Progress> progress) {
checkCancelled();
progress.accept(new Progress("searching", "正在检索社区项目"));
List<String> patterns = intent.keywords().stream().map(this::pattern).toList();
List<Project> pool =
candidates.candidates(intent.projectType(), patterns, intent.focusProjectCodes());
log.info("Maker AI 候选检索完成 candidateCount={}", pool.size());
if (pool.isEmpty()) return noMatch();
checkCancelled();
progress.accept(new Progress("ranking", "正在整理匹配结果"));
ObjectNode ranking = json.createObjectNode();
ranking.set("intent", json.valueToTree(intent));
ranking.put("forFork", forFork);
ArrayNode entries = ranking.putArray("candidates");
pool.forEach(project -> entries.add(snapshot(project)));
JsonNode raw =
model.complete(
"vibemake_search_ranking",
rules.rankingSchema(),
rules.rankingPrompt(),
ranking);
checkCancelled();
progress.accept(new Progress("validating", "正在核对项目与匹配依据"));
return results(userId, intent, pool, raw);
}
private ChatResult results(long userId, Criteria intent, List<Project> pool, JsonNode node) {
fields(node, "selections");
JsonNode selections = node.get("selections");
array(selections, 5);
Map<String, Project> known = byCode(pool);
List<ProjectCard> cards = new ArrayList<>();
Set<String> chosen = new HashSet<>();
// 先完整校验模型结果,再读取最新记录;避免把伪造结果当成“未找到”。
List<ValidatedCard> validated = new ArrayList<>();
for (JsonNode item : selections) {
fields(item, "projectCode", "reason", "evidence");
String code = text(item.get("projectCode"), 32, false);
Project project = known.get(code);
if (project == null || !chosen.add(code)) throw invalid("unknown_or_duplicate_project");
String reason = text(item.get("reason"), 400, false);
array(item.get("evidence"), 12);
if (item.get("evidence").isEmpty()) throw invalid("empty_evidence");
Set<Integer> required = new HashSet<>();
Set<Integer> preferred = new HashSet<>();
List<Evidence> evidence = new ArrayList<>();
for (JsonNode proof : item.get("evidence")) {
fields(proof, "field", "quote", "requirementIndex", "preferenceIndex");
String field = text(proof.get("field"), 20, false);
String quote = text(proof.get("quote"), 300, false);
String source =
switch (field) {
case "name" -> project.getName();
case "description" -> project.getDescription();
case "projectType" -> project.getProjectType();
default -> throw invalid("unknown_evidence_field");
};
if (source == null || !source.contains(quote)) throw invalid("quote_not_in_source");
Integer requirement =
index(proof.get("requirementIndex"), intent.requirements().size());
Integer preference =
index(proof.get("preferenceIndex"), intent.preferences().size());
if (requirement != null) {
// 类型不能证明技术能力;明确要求必须引用名称或描述。
if ("projectType".equals(field)) throw invalid("type_cannot_prove_capability");
required.add(requirement);
evidence.add(
new Evidence(field, quote, intent.requirements().get(requirement)));
}
if (preference != null) {
preferred.add(preference);
evidence.add(new Evidence(field, quote, intent.preferences().get(preference)));
}
if (requirement == null && preference == null)
evidence.add(new Evidence(field, quote, null));
}
if (required.size() != intent.requirements().size())
throw invalid("missing_required_evidence");
List<String> unknown = new ArrayList<>();
for (int index = 0; index < intent.preferences().size(); index++)
if (!preferred.contains(index)) unknown.add(intent.preferences().get(index));
validated.add(
new ValidatedCard(
project, reason, List.copyOf(evidence), List.copyOf(unknown)));
}
Map<String, Project> current = byCode(visible(new ArrayList<>(chosen)));
List<Project> visibleCards =
validated.stream()
.filter(
card ->
current.get(card.project().getProjectCode()) != null
&& sameSnapshot(
card.project(),
current.get(
card.project().getProjectCode())))
.map(card -> current.get(card.project().getProjectCode()))
.toList();
Map<String, com.linkerbot.vibemake.bean.Contracts.ProjectView> views = new HashMap<>();
projectService
.views(visibleCards, userId)
.forEach(view -> views.put(view.projectCode(), view));
for (ValidatedCard card : validated) {
checkCancelled();
Project latest = current.get(card.project().getProjectCode());
// 描述、类型或发布版本变化后,旧依据不再用于新的结果。
if (latest == null || !sameSnapshot(card.project(), latest)) continue;
cards.add(
new ProjectCard(
views.get(latest.getProjectCode()),
card.reason(),
card.evidence(),
card.unknown()));
}
if (cards.isEmpty()) return noMatch();
return new ChatResult(
Status.MATCHED,
"为你找到 " + cards.size() + " 个候选项目,请结合匹配依据和未确认事项查看详情。",
List.copyOf(cards));
}
private boolean sameSnapshot(Project before, Project after) {
return Objects.equals(before.getName(), after.getName())
&& Objects.equals(before.getDescription(), after.getDescription())
&& Objects.equals(before.getProjectType(), after.getProjectType())
&& Objects.equals(before.getPublishedCommitSha(), after.getPublishedCommitSha());
}
List<Project> visible(List<String> codes) {
if (codes.isEmpty()) return List.of();
return projects.selectList(
new LambdaQueryWrapper<Project>()
.select(Project.class, field -> !"urdfFiles".equals(field.getProperty()))
.in(Project::getProjectCode, codes)
.eq(Project::getDeleted, false)
.eq(Project::getRepoStatus, "READY")
.eq(Project::getPublishStatus, "PUBLISHED"));
}
private Map<String, Project> byCode(List<Project> records) {
Map<String, Project> result = new HashMap<>();
records.forEach(project -> result.put(project.getProjectCode(), project));
return result;
}
ObjectNode snapshot(Project project) {
return json.createObjectNode()
.put("projectCode", project.getProjectCode())
.put("name", project.getName())
.put("description", project.getDescription())
.put("projectType", project.getProjectType());
}
private String pattern(String word) {
return "%"
+ word.toLowerCase(Locale.ROOT)
.replace("!", "!!")
.replace("%", "!%")
.replace("_", "!_")
+ "%";
}
private void checkCancelled() {
if (Thread.currentThread().isInterrupted())
throw new BusinessException(499, "AI_CANCELLED", "Maker AI 已取消");
}
private ChatResult noMatch() {
return new ChatResult(Status.NO_MATCH, "暂未找到有充分资料匹配要求的社区项目,可以尝试调整类型或减少条件。", List.of());
}
private record ValidatedCard(
Project project, String reason, List<Evidence> evidence, List<String> unknown) {}
}
@@ -0,0 +1,54 @@
package com.linkerbot.vibemake.service.ai;
import com.fasterxml.jackson.databind.JsonNode;
import com.linkerbot.vibemake.common.BusinessException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** JSON Schema 之外的服务端校验,模型输出始终按不可信输入处理。 */
final class AiResponseValidation {
private static final Logger log = LoggerFactory.getLogger(AiResponseValidation.class);
private AiResponseValidation() {}
static List<String> strings(JsonNode node, int maximum, int length) {
array(node, maximum);
List<String> values = new ArrayList<>();
for (JsonNode item : node) values.add(text(item, length, false));
return values.stream().distinct().toList();
}
static void array(JsonNode node, int maximum) {
if (node == null || !node.isArray() || node.size() > maximum) throw invalid("array_shape_or_length");
}
static void fields(JsonNode node, String... expected) {
if (node == null || !node.isObject() || node.size() != expected.length) throw invalid("object_shape");
for (String field : expected) if (!node.has(field)) throw invalid("missing_field");
}
static String text(JsonNode node, int maximum, boolean emptyAllowed) {
if (node == null || !node.isTextual() || node.textValue().length() > maximum
|| (!emptyAllowed && node.textValue().isBlank())) throw invalid("text_shape_or_length");
return node.textValue().trim();
}
static String nullableText(JsonNode node, int maximum, boolean emptyAllowed) {
if (node != null && node.isNull()) return null;
return text(node, maximum, emptyAllowed);
}
static Integer index(JsonNode node, int size) {
if (node != null && node.isNull()) return null;
if (node == null || !node.isIntegralNumber() || !node.canConvertToInt()
|| node.intValue() < 0 || node.intValue() >= size) throw invalid("index_out_of_range");
return node.intValue();
}
static BusinessException invalid(String rule) {
log.warn("Maker AI 结果校验失败 validationRule={}", rule);
return new BusinessException(502, "AI_INVALID_RESPONSE", "Maker AI 结果未通过校验,请稍后重试");
}
}
@@ -0,0 +1,47 @@
package com.linkerbot.vibemake.service.ai;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.linkerbot.vibemake.service.config.VibemakeProperties;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
@Component
public class AiSearchRules {
private final ObjectNode intentSchema;
private final JsonNode rankingSchema;
private final String intentPrompt;
private final String rankingPrompt;
private final VibemakeProperties properties;
public AiSearchRules(ObjectMapper json, VibemakeProperties properties) throws IOException {
this.properties = properties;
intentSchema = (ObjectNode) json.readTree(read("intent.schema.json"));
rankingSchema = json.readTree(read("ranking.schema.json"));
intentPrompt = read("intent-prompt.txt");
rankingPrompt = read("ranking-prompt.txt");
}
public JsonNode intentSchema() {
ObjectNode schema = intentSchema.deepCopy();
ArrayNode types = ((ObjectNode) schema.path("properties").path("projectType")).putArray("enum");
properties.getTypes().keySet().forEach(types::add);
types.addNull();
return schema;
}
public JsonNode rankingSchema() { return rankingSchema.deepCopy(); }
public String intentPrompt() { return intentPrompt; }
public String rankingPrompt() { return rankingPrompt; }
private String read(String name) throws IOException {
try (InputStream input = new ClassPathResource("ai-search/" + name).getInputStream()) {
return new String(input.readAllBytes(), StandardCharsets.UTF_8);
}
}
}
@@ -0,0 +1,124 @@
package com.linkerbot.vibemake.service.ai;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.config.AiProperties;
import java.net.URI;
import java.net.http.*;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/** 方舟 Responses API;非流式结构化输出,不保存上游响应。 */
@Component
public class ArkAiClient implements AiModelClient {
private static final Logger log = LoggerFactory.getLogger(ArkAiClient.class);
private final ObjectMapper json;
private final AiProperties properties;
private final HttpClient http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build();
public ArkAiClient(ObjectMapper json, AiProperties properties) {
this.json = json;
this.properties = properties;
}
@Override
public JsonNode complete(String schemaName, JsonNode schema, String systemPrompt, JsonNode input) {
if (!properties.isEnabled() || properties.getApiKey() == null || properties.getApiKey().isBlank())
throw new BusinessException(503, "AI_UNAVAILABLE", "Maker AI 暂未开启");
CompletableFuture<HttpResponse<byte[]>> pending = null;
try {
ObjectNode body = json.createObjectNode().put("model", properties.getModel())
.put("stream", false).put("store", false).put("max_output_tokens", 4096);
body.putObject("thinking").put("type", "disabled");
body.putObject("text").putObject("format").put("type", "json_schema")
.put("name", schemaName).put("strict", true).set("schema", schema);
body.putArray("input").addObject().put("role", "system").put("content", systemPrompt);
body.withArray("input").addObject().put("role", "user").put("content", json.writeValueAsString(input));
byte[] payload = json.writeValueAsBytes(body);
if (payload.length > 256 * 1024) throw BusinessException.badRequest("Maker AI 输入过长");
HttpRequest request = HttpRequest.newBuilder(URI.create(properties.getEndpoint()))
.timeout(properties.getRequestTimeout())
.header("Authorization", "Bearer " + properties.getApiKey())
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofByteArray(payload)).build();
pending = http.sendAsync(request, info -> new LimitedBodySubscriber());
HttpResponse<byte[]> response = pending.get(properties.getRequestTimeout().toMillis(), TimeUnit.MILLISECONDS);
if (response.statusCode() < 200 || response.statusCode() >= 300) {
log.warn("Maker AI 方舟请求失败 httpStatus={}", response.statusCode());
throw failure();
}
JsonNode data = read(response.body());
if (!"completed".equals(data.path("status").asText()) || !data.path("output").isArray()) throw failure();
StringBuilder result = new StringBuilder();
for (JsonNode item : data.path("output")) {
if (!"message".equals(item.path("type").asText())) continue;
for (JsonNode content : item.path("content"))
if ("output_text".equals(content.path("type").asText())) result.append(content.path("text").asText());
}
if (result.isEmpty()) throw failure();
JsonNode parsed = read(result.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8));
if (!parsed.isObject()) throw failure();
return parsed;
} catch (TimeoutException error) {
throw timeout();
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw new BusinessException(499, "AI_CANCELLED", "Maker AI 已取消");
} catch (ExecutionException error) {
if (error.getCause() instanceof HttpTimeoutException) throw timeout();
log.warn("Maker AI 方舟响应异常 exceptionType={}", error.getCause().getClass().getSimpleName());
throw failure();
} catch (BusinessException error) {
throw error;
} catch (Exception error) {
log.warn("Maker AI 方舟响应异常 exceptionType={}", error.getClass().getSimpleName());
throw failure();
} finally {
if (pending != null && !pending.isDone()) pending.cancel(true);
}
}
private JsonNode read(byte[] bytes) throws java.io.IOException {
return json.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
.with(JsonParser.Feature.STRICT_DUPLICATE_DETECTION).readTree(bytes);
}
private BusinessException failure() {
return new BusinessException(502, "AI_PROVIDER_FAILURE", "Maker AI 服务返回异常,请稍后重试");
}
private BusinessException timeout() {
return new BusinessException(504, "AI_TIMEOUT", "Maker AI 超时,请稍后重试");
}
private static final class LimitedBodySubscriber implements HttpResponse.BodySubscriber<byte[]> {
private final HttpResponse.BodySubscriber<byte[]> delegate = HttpResponse.BodySubscribers.ofByteArray();
private Flow.Subscription subscription;
private long received;
@Override public CompletionStage<byte[]> getBody() { return delegate.getBody(); }
@Override public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
delegate.onSubscribe(subscription);
}
@Override public void onNext(List<ByteBuffer> buffers) {
for (ByteBuffer buffer : buffers) received += buffer.remaining();
if (received > 1024 * 1024) {
subscription.cancel();
delegate.onError(new IllegalStateException("AI response size exceeded"));
} else delegate.onNext(buffers);
}
@Override public void onError(Throwable error) { delegate.onError(error); }
@Override public void onComplete() { delegate.onComplete(); }
}
}
@@ -0,0 +1,30 @@
package com.linkerbot.vibemake.service.config;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import java.time.Duration;
import java.util.List;
@Getter
@Setter
@Component
@Validated
@ConfigurationProperties(prefix = "vibemake.admin")
public class AdminProperties {
private List<String> allowedOrigins = List.of();
private String githubToken = "";
private boolean workerEnabled = true;
private Duration migrationTimeout = Duration.ofMinutes(30);
@Min(1)
@Max(4)
private int importConcurrency = 2;
}
@@ -0,0 +1,58 @@
package com.linkerbot.vibemake.service.config;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import java.net.URI;
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.ai")
public class AiProperties {
private boolean enabled;
private String apiKey = "";
@NotBlank private String model = "doubao-seed-2-1-lite-260915";
@NotBlank private String endpoint = "https://ark.cn-beijing.volces.com/api/v3/responses";
private Duration requestTimeout = Duration.ofSeconds(30);
private Duration searchTimeout = Duration.ofSeconds(65);
private Duration heartbeatInterval = Duration.ofSeconds(10);
@Min(1) @Max(32) private int maxConcurrent = 4;
@Min(1) @Max(120) private int requestsPerMinute = 10;
@AssertTrue(message = "开启 AI 时必须配置 ARK_API_KEY")
public boolean isApiKeyConfigured() {
return !enabled || (apiKey != null && !apiKey.isBlank());
}
@AssertTrue(message = "AI 超时及心跳配置不合法")
public boolean isTimingValid() {
return validDuration(requestTimeout, 300000) && validDuration(searchTimeout, 600000)
&& validDuration(heartbeatInterval, 60000)
&& heartbeatInterval.compareTo(searchTimeout) < 0;
}
@AssertTrue(message = "AI endpoint 必须是无凭据的 HTTP(S) 地址")
public boolean isEndpointValid() {
try {
URI uri = URI.create(endpoint);
return ("https".equals(uri.getScheme()) || "http".equals(uri.getScheme()))
&& uri.getHost() != null && uri.getUserInfo() == null && uri.getFragment() == null;
} catch (RuntimeException error) {
return false;
}
}
private boolean validDuration(Duration value, long maximumMillis) {
return value != null && value.compareTo(Duration.ofMillis(100)) >= 0
&& value.compareTo(Duration.ofMillis(maximumMillis)) <= 0;
}
}
@@ -0,0 +1,33 @@
package com.linkerbot.vibemake.service.config;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import java.nio.file.Path;
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.fork")
public class ForkProperties {
@NotBlank private String gitExecutable = "git";
private Duration timeout = Duration.ofMinutes(5);
@Min(1) @Max(32) private int maxConcurrent = 2;
@Positive private long maxTemporaryBytes = 5L * 1024 * 1024 * 1024;
@NotBlank private String temporaryDirectory = Path.of(System.getProperty("java.io.tmpdir"), "vibemake-fork").toString();
@AssertTrue(message = "Fork 超时必须在 100 毫秒至 1 小时之间")
public boolean isTimeoutValid() {
return timeout != null && timeout.compareTo(Duration.ofMillis(100)) >= 0
&& timeout.compareTo(Duration.ofHours(1)) <= 0;
}
}
@@ -0,0 +1,61 @@
package com.linkerbot.vibemake.service.config;
import jakarta.validation.constraints.AssertTrue;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Getter
@Setter
@Validated
@Component
@ConfigurationProperties("vibemake.limits")
public class LimitProperties {
private boolean enabled = true;
private List<String> trustedProxies = List.of();
private Map<String, Integer> perMinute = defaults();
private long jsonBytes = 256 * 1024;
private long urdfJsonBytes = 2 * 1024 * 1024;
private long commitJsonBytes = 64 * 1024 * 1024;
private int fileConcurrent = 4;
private static Map<String, Integer> defaults() {
Map<String, Integer> values = new LinkedHashMap<>();
values.put("captcha", 20);
values.put("login-ip", 20);
values.put("login-account", 10);
values.put("admin-login", 30);
values.put("vibemake-read", 120);
values.put("file-read", 60);
values.put("create", 5);
values.put("fork", 10);
values.put("file-write", 10);
values.put("cover-sign", 30);
values.put("urdf-sign", 20);
values.put("comment", 10);
values.put("like", 60);
return values;
}
@AssertTrue(message = "限流及请求保护配置不合法")
public boolean isValid() {
return perMinute != null
&& perMinute.keySet().containsAll(defaults().keySet())
&& perMinute.values().stream().allMatch(n -> n != null && n > 0 && n <= 100000)
&& jsonBytes > 0
&& urdfJsonBytes > 0
&& commitJsonBytes > 0
&& commitJsonBytes <= 256L * 1024 * 1024
&& fileConcurrent > 0
&& fileConcurrent <= 64
&& trustedProxies != null;
}
}
@@ -0,0 +1,18 @@
package com.linkerbot.vibemake.service.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisConfiguration {
@Bean
public MybatisPlusInterceptor paginationInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
@@ -0,0 +1,75 @@
package com.linkerbot.vibemake.service.config;
import jakarta.validation.constraints.AssertTrue;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
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.oss")
public class OssProperties {
private boolean enabled;
private String region = "";
private String endpoint = "";
private String bucket = "";
private String accessKeyId = "";
private String accessKeySecret = "";
private String publicBaseUrl = "";
private String rootDirectory = "";
private List<String> legacyPublicBaseUrls = new ArrayList<>();
@AssertTrue(message = "历史 OSS/CDN 基础地址必须是无凭据、查询参数及片段的 HTTPS 地址")
public boolean isLegacyPublicBaseUrlsValid() {
return legacyPublicBaseUrls != null
&& legacyPublicBaseUrls.stream().allMatch(value -> validBaseUrl(value, true));
}
@AssertTrue(message = "开启 OSS 时必须配置合法的地域 ID(如 cn-beijing)、Bucket、凭据及根目录;Endpoint 为可选 HTTPS 地址")
public boolean isConfigurationValid() {
if (!enabled) return true;
return region != null && region.matches("[a-z0-9]+(?:-[a-z0-9]+)+")
&& !region.startsWith("oss-")
&& bucket != null && bucket.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]")
&& accessKeyId != null && accessKeyId.matches("[A-Za-z0-9]+")
&& accessKeySecret != null && !accessKeySecret.isBlank()
&& rootDirectory != null && rootDirectory.matches("[A-Za-z0-9_-]+")
&& validBaseUrl(resolvedEndpoint(), false)
&& (publicBaseUrl != null
&& (publicBaseUrl.isBlank() || validBaseUrl(publicBaseUrl, true)));
}
private boolean validBaseUrl(String value, boolean allowPath) {
try {
URI uri = URI.create(value);
return "https".equals(uri.getScheme()) && uri.getHost() != null
&& uri.getRawUserInfo() == null && uri.getRawQuery() == null
&& uri.getRawFragment() == null
&& (uri.getPort() == -1 || (uri.getPort() > 0 && uri.getPort() <= 65535))
&& (allowPath || uri.getRawPath().isEmpty() || "/".equals(uri.getRawPath()));
} catch (IllegalArgumentException | NullPointerException error) {
return false;
}
}
public String uploadUrl() {
URI uri = URI.create(resolvedEndpoint());
return "https://" + bucket + "." + uri.getRawAuthority();
}
public String resolvedEndpoint() {
return endpoint == null || endpoint.isBlank()
? "https://oss-" + region + ".aliyuncs.com" : endpoint;
}
public String publicBaseUrl() {
return publicBaseUrl.isBlank() ? uploadUrl() : publicBaseUrl.replaceAll("/+$", "");
}
}
@@ -0,0 +1,27 @@
package com.linkerbot.vibemake.service.config;
import jakarta.validation.constraints.Pattern;
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
@Component
@Validated
@ConfigurationProperties("vibemake.redis")
public class RedisStateProperties {
@Pattern(regexp = "[A-Za-z0-9:_-]{1,100}")
private String keyPrefix = "vibemake:test";
@Pattern(regexp = "api|admin")
private String application = "api";
public String prefix() {
return keyPrefix + ":" + application + ":v1:";
}
}
@@ -0,0 +1,19 @@
package com.linkerbot.vibemake.service.config;
import jakarta.validation.constraints.Positive;
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.oss.urdf")
public class UrdfProperties {
@Positive private long maxFileBytes = 50L * 1024 * 1024;
@Positive private long maxTotalBytes = 200L * 1024 * 1024;
@Positive private int maxFiles = 500;
}
@@ -0,0 +1,45 @@
package com.linkerbot.vibemake.service.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "vibemake")
public class VibemakeProperties {
private Map<String, String> types = defaultTypes();
private long maxTextBytes = 1024 * 1024;
private long maxFileBytes = 10 * 1024 * 1024;
private long maxRequestBytes = 50 * 1024 * 1024;
private Duration captchaTtl = Duration.ofMinutes(2);
private Duration tokenTtl = Duration.ofHours(24);
private Gitea gitea = new Gitea();
private static Map<String, String> defaultTypes() {
Map<String, String> types = new LinkedHashMap<>();
types.put("GENERAL", "通用");
types.put("HUMANOID", "人形");
types.put("QUADRUPED", "四足");
types.put("WHEELED", "轮式");
types.put("ROBOTIC_ARM", "机械臂");
return types;
}
@Getter
@Setter
public static class Gitea {
private String baseUrl = "http://localhost:3000";
private String owner = "vibemake";
private String token = "";
private Duration connectTimeout = Duration.ofSeconds(5);
private Duration requestTimeout = Duration.ofSeconds(30);
}
}
@@ -0,0 +1,268 @@
package com.linkerbot.vibemake.service.fork;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.common.FilePaths;
import com.linkerbot.vibemake.service.config.VibemakeProperties;
import com.linkerbot.vibemake.service.config.ForkProperties;
import com.linkerbot.vibemake.service.gitea.GiteaClient;
import com.linkerbot.vibemake.service.gitea.GiteaClient.Repository;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;
import java.time.Duration;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/** 使用原始 Git tree 生成根提交,不检出文件、不递归子模块、不复制上游历史。 */
@Component
public class CliGitSnapshotCopier implements GitSnapshotCopier {
private static final Logger log = LoggerFactory.getLogger(CliGitSnapshotCopier.class);
private final ForkProperties properties;
private final VibemakeProperties vibemake;
private final GitCommandRunner commands;
private final GiteaClient gitea;
private final ObjectMapper json;
public CliGitSnapshotCopier(ForkProperties properties, VibemakeProperties vibemake, GitCommandRunner commands,
GiteaClient gitea, ObjectMapper json) {
this.properties = properties;
this.vibemake = vibemake;
this.commands = commands;
this.gitea = gitea;
this.json = json;
}
@Override
public void checkAvailable() {
try {
trustedBase();
if (vibemake.getGitea().getToken().isBlank()) throw unavailable();
ForkDeadline deadline = new ForkDeadline(Duration.ofSeconds(5));
if (commands.run(null, deadline, "git-runtime", Map.of(), Map.of(), "--version").exitCode() != 0
|| commands.run(null, deadline, "lfs-runtime", Map.of(), Map.of(), "lfs", "version").exitCode() != 0)
throw unavailable();
Path root = Files.createDirectories(Path.of(properties.getTemporaryDirectory()));
Path probe = Files.createTempFile(root, ".fork-probe-", ".tmp");
Files.delete(probe);
} catch (IOException | RuntimeException error) {
throw unavailable();
}
}
private BusinessException unavailable() {
return new BusinessException(503, "FORK_UNAVAILABLE", "Fork 不可用,请检查 Git、git-lfs、Gitea 配置和临时目录");
}
protected URI trustedBase() {
URI base = URI.create(vibemake.getGitea().getBaseUrl().replaceAll("/+$", ""));
if (!("http".equals(base.getScheme()) || "https".equals(base.getScheme())) || base.getHost() == null
|| base.getRawUserInfo() != null || base.getRawQuery() != null || base.getRawFragment() != null)
throw unavailable();
return base;
}
protected String repositoryUrl(Repository repository) {
String owner = URLEncoder.encode(repository.owner(), StandardCharsets.UTF_8).replace("+", "%20");
String name = URLEncoder.encode(repository.name(), StandardCharsets.UTF_8).replace("+", "%20");
return trustedBase() + "/" + owner + "/" + name + ".git";
}
protected Map<String, String> configuration(String lfsEndpoint) {
String username = gitea.authenticatedUsername();
if (username == null || username.isBlank()) throw unavailable();
String basic = Base64.getEncoder().encodeToString((username + ":" + vibemake.getGitea().getToken()).getBytes(StandardCharsets.UTF_8));
Map<String, String> settings = new LinkedHashMap<>();
settings.put("http." + trustedBase() + "/.extraHeader", "Authorization: Basic " + basic);
settings.put("lfs.url", lfsEndpoint);
settings.put("lfs.pushurl", lfsEndpoint);
settings.put("lfs.fetchinclude", "");
settings.put("lfs.fetchexclude", "");
settings.put("lfs.fetchrecentalways", "false");
settings.put("lfs.fetchrecentrefsdays", "0");
settings.put("lfs.fetchrecentcommitsdays", "0");
settings.put("lfs.basictransfersonly", "true");
settings.put("lfs.standalonetransferagent", "");
settings.put("lfs.transfer.maxretries", "1");
settings.put("lfs.transfer.maxverifies", "1");
settings.put("lfs.transfer.maxretrydelay", "0");
settings.put("lfs.concurrenttransfers", "2");
return settings;
}
@Override
public PreparedSnapshot prepare(Repository source, String publishedSha, String authorName, String authorCode,
ForkDeadline deadline) {
String sha = FilePaths.sha(publishedSha);
Path workspace = null;
Snapshot snapshot = null;
try {
deadline.check();
workspace = Files.createTempDirectory(Path.of(properties.getTemporaryDirectory()), "fork-" + deadline.projectCode() + "-");
Files.setPosixFilePermissions(workspace, PosixFilePermissions.fromString("rwx------"));
String url = repositoryUrl(source);
Map<String, String> settings = configuration(url + "/info/lfs");
snapshot = new Snapshot(workspace, deadline, settings);
snapshot.require("init", "init", "--bare", "--quiet");
blockLfsLogs(workspace.resolve("lfs"));
snapshot.require("source-remote", "remote", "add", "source", url);
GitCommandRunner.Result fetched = snapshot.run("fetch-sha", "fetch", "--quiet", "--depth=1", "--no-tags", "source", sha);
if (fetched.exitCode() != 0) {
boolean shallow = snapshot.require("shallow-check", "rev-parse", "--is-shallow-repository").equals("true");
if (shallow) snapshot.require("fetch-main", "fetch", "--quiet", "--no-tags", "--unshallow", "source", "refs/heads/main");
else snapshot.require("fetch-main", "fetch", "--quiet", "--no-tags", "source", "refs/heads/main");
}
snapshot.require("source-check", "cat-file", "-e", sha + "^{commit}");
snapshot.tree = FilePaths.sha(snapshot.require("source-tree", "rev-parse", sha + "^{tree}"));
String author = authorName == null ? "Vibemake user" : authorName.replaceAll("[\\r\\n<>\\x00]", " ").trim();
if (author.isEmpty()) author = "Vibemake user";
Map<String, String> identity = Map.of("GIT_AUTHOR_NAME", author, "GIT_COMMITTER_NAME", author,
"GIT_AUTHOR_EMAIL", authorCode + "@users.vibemake.invalid", "GIT_COMMITTER_EMAIL", authorCode + "@users.vibemake.invalid");
GitCommandRunner.Result commit = commands.run(workspace, deadline, "root-commit", settings, identity,
"commit-tree", snapshot.tree, "-m", "Fork vibemake snapshot");
if (commit.exitCode() != 0) throw GitCommandRunner.failed(deadline);
snapshot.commit = FilePaths.sha(commit.output());
snapshot.require("snapshot-ref", "update-ref", "refs/heads/snapshot", snapshot.commit);
snapshot.require("snapshot-head", "symbolic-ref", "HEAD", "refs/heads/snapshot");
String parents = snapshot.require("root-check", "rev-list", "--parents", "-n", "1", snapshot.commit);
if (!parents.equals(snapshot.commit)) throw GitCommandRunner.failed(deadline);
JsonNode listing = json.readTree(snapshot.require("lfs-list", "lfs", "ls-files", "--json", sha));
JsonNode objects = listing == null ? null : listing.get("files");
if (objects == null || !(objects.isArray() || objects.isNull())) throw GitCommandRunner.failed(deadline);
snapshot.hasLfs = objects.isArray() && !objects.isEmpty();
if (snapshot.hasLfs) {
snapshot.protectLfs();
snapshot.require("lfs-fetch", "lfs", "fetch", "--include=", "--exclude=", "source", sha);
snapshot.require("lfs-fsck", "lfs", "fsck", "--objects", sha);
}
log.info("Fork 快照准备完成 projectCode={} sourceRepository={} sourceCommitSha={} snapshotCommitSha={} hasLfs={}",
deadline.projectCode(), source.name(), sha, snapshot.commit, snapshot.hasLfs);
return snapshot;
} catch (IOException error) {
if (snapshot != null) snapshot.close();
else if (workspace != null) clean(workspace, deadline.projectCode());
throw GitCommandRunner.failed(deadline);
} catch (RuntimeException error) {
if (snapshot != null) snapshot.close();
else if (workspace != null) clean(workspace, deadline.projectCode());
throw error;
}
}
private final class Snapshot implements PreparedSnapshot {
private final Path workspace;
private final ForkDeadline deadline;
private Map<String, String> settings;
private String tree;
private String commit;
private boolean hasLfs;
private LfsEndpointGuard lfsGuard;
private Snapshot(Path workspace, ForkDeadline deadline, Map<String, String> settings) {
this.workspace = workspace;
this.deadline = deadline;
this.settings = settings;
}
private GitCommandRunner.Result run(String stage, String... args) {
return commands.run(workspace, deadline, stage, settings, Map.of(), args);
}
private String require(String stage, String... args) {
GitCommandRunner.Result result = run(stage, args);
if (result.exitCode() != 0) {
if (result.rejected()) deadline.confirmWrite();
throw GitCommandRunner.failed(deadline);
}
return result.output();
}
private void protectLfs() {
if (lfsGuard != null) lfsGuard.close();
try {
String header = settings.get("http." + trustedBase() + "/.extraHeader");
lfsGuard = new LfsEndpointGuard(trustedBase(), URI.create(settings.get("lfs.url")),
header.substring("Authorization: ".length()), deadline, json);
settings.put("lfs.url", lfsGuard.endpoint());
settings.put("lfs.pushurl", lfsGuard.endpoint());
settings.put("http." + lfsGuard.endpoint() + "/.extraHeader", "Authorization: " + lfsGuard.localAuthorization());
} catch (IOException error) { throw GitCommandRunner.failed(deadline); }
}
@Override
public String push(Repository target) {
String url = repositoryUrl(target);
settings = configuration(url + "/info/lfs");
if (hasLfs) protectLfs();
require("target-remote", "remote", "add", "target", url);
if (!require("snapshot-tree", "rev-parse", commit + "^{tree}").equals(tree)) throw GitCommandRunner.failed(deadline);
if (hasLfs) {
deadline.beginWrite();
require("lfs-push", "lfs", "push", "--all", "target", "refs/heads/snapshot");
deadline.confirmWrite();
}
deadline.beginWrite();
require("git-push", "push", "--quiet", "target", commit + ":refs/heads/main");
String remote = require("target-check", "ls-remote", "target", "refs/heads/main");
if (!remote.equals(commit + "\trefs/heads/main")) throw GitCommandRunner.failed(deadline);
deadline.confirmWrite();
verifyRemote(target, commit, deadline);
if (hasLfs) {
// 用独立缓存从副本下载,确认不依赖来源的本地缓存且实体完整。
try { blockLfsLogs(workspace.resolve("verified-lfs")); }
catch (IOException error) { throw GitCommandRunner.failed(deadline); }
settings.put("lfs.storage", workspace.resolve("verified-lfs").toString());
require("lfs-verify-fetch", "lfs", "fetch", "--include=", "--exclude=", "target", commit);
require("lfs-verify-fsck", "lfs", "fsck", "--objects", commit);
}
deadline.check();
return commit;
}
@Override public void close() {
if (lfsGuard != null) lfsGuard.close();
clean(workspace, deadline.projectCode());
}
}
protected void verifyRemote(Repository target, String commit, ForkDeadline deadline) {
// Gitea 首次推送的元数据由服务端同步;在 empty 清除之前访问分支 API 可能失败。
while (gitea.inspect(target.name()).empty()) {
deadline.check();
try { Thread.sleep(Math.min(100, Math.max(1, deadline.remaining().toMillis()))); }
catch (InterruptedException error) { Thread.currentThread().interrupt(); throw deadline.failure(); }
}
if (!gitea.head(target).equals(commit)) throw GitCommandRunner.failed(deadline);
}
private void blockLfsLogs(Path storage) throws IOException {
// git-lfs 错误报告会写入全部 GIT_* 环境,必须在任何 LFS 命令前阻止落盘。
Files.createDirectories(storage);
Files.createFile(storage.resolve("logs"));
}
private void clean(Path directory, String projectCode) {
try {
Files.walkFileTree(directory, new SimpleFileVisitor<>() {
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
Files.deleteIfExists(file);
return FileVisitResult.CONTINUE;
}
@Override public FileVisitResult postVisitDirectory(Path folder, IOException error) throws IOException {
if (error != null) throw error;
Files.deleteIfExists(folder);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException error) {
log.warn("Fork 临时目录清理失败 projectCode={} errorType={}", projectCode, error.getClass().getSimpleName());
}
}
}
@@ -0,0 +1,73 @@
package com.linkerbot.vibemake.service.fork;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.gitea.GiteaFailure;
import java.time.Duration;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** 一次 Fork 的截止时间和远端写入状态;仅在其独立工作线程内绑定。 */
public final class ForkDeadline {
private static final Logger log = LoggerFactory.getLogger(ForkDeadline.class);
private static final ThreadLocal<ForkDeadline> CURRENT = new ThreadLocal<>();
private final long expires;
private volatile String projectCode;
private volatile boolean writing;
private volatile String cancellation;
private final List<Runnable> cleanup = new ArrayList<>();
public ForkDeadline(Duration timeout) { expires = System.nanoTime() + timeout.toNanos(); }
static void bind(ForkDeadline deadline) { CURRENT.set(deadline); }
static void unbind() { CURRENT.remove(); }
public static ForkDeadline current() { return CURRENT.get(); }
public void projectCode(String code) { projectCode = code; }
public String projectCode() { return projectCode; }
public boolean writing() { return writing; }
public void onClose(Runnable action) { cleanup.add(action); }
void closeResources() {
for (Runnable action : cleanup) {
try { action.run(); }
catch (RuntimeException error) { log.warn("Fork 资源关闭失败 projectCode={} errorType={}", projectCode, error.getClass().getSimpleName()); }
}
cleanup.clear();
}
public static void checkpoint() {
ForkDeadline deadline = current();
if (deadline != null) deadline.check();
}
public void check() {
if (cancellation != null || Thread.currentThread().isInterrupted() || System.nanoTime() >= expires)
throw failure();
}
public Duration remaining() {
check();
return Duration.ofNanos(Math.max(1, expires - System.nanoTime()));
}
public static Duration bounded(Duration maximum) {
ForkDeadline deadline = current();
if (deadline == null) return maximum;
Duration remaining = deadline.remaining();
return remaining.compareTo(maximum) < 0 ? remaining : maximum;
}
public synchronized void beginWrite() { check(); writing = true; }
public synchronized void confirmWrite() { writing = false; }
synchronized void cancel(String code) { cancellation = code; }
public BusinessException failure() {
String code = cancellation == null ? "FORK_TIMEOUT" : cancellation;
String message = "Fork 已超时或取消,请先核对工作区项目状态";
if (writing) return new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", message, true);
return new BusinessException(code.equals("FORK_CANCELLED") ? 499 : 504, code, message, details());
}
public Map<String, String> details() { return projectCode == null ? null : Map.of("projectCode", projectCode); }
}
@@ -0,0 +1,121 @@
package com.linkerbot.vibemake.service.fork;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.config.ForkProperties;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.util.concurrent.*;
import java.util.function.Function;
/** 同步等待结果,但工作线程及并发名额的生命周期不依赖 HTTP 连接。 */
@Component
public class ForkExecutor {
private static final Logger log = LoggerFactory.getLogger(ForkExecutor.class);
private final ForkProperties properties;
private final GitSnapshotCopier copier;
private final Semaphore permits;
private final ExecutorService workers =
Executors.newThreadPerTaskExecutor(
Thread.ofVirtual().name("project-fork-", 0).factory());
private final Set<FutureTask<?>> active = ConcurrentHashMap.newKeySet();
public ForkExecutor(ForkProperties properties, GitSnapshotCopier copier) {
this.properties = properties;
this.copier = copier;
permits = new Semaphore(properties.getMaxConcurrent());
}
@PostConstruct
public void inspectRuntime() {
try {
copier.checkAvailable();
} catch (BusinessException error) {
log.warn("Fork 运行依赖不可用 code={}", error.code());
}
}
public <T> T execute(Function<ForkDeadline, T> action) {
ForkDeadline deadline = new ForkDeadline(properties.getTimeout());
if (!permits.tryAcquire())
throw new com.linkerbot.vibemake.common.RateLimitedException(
"FORK_BUSY", "Fork 繁忙,请稍后手动重试", 1);
try {
copier.checkAvailable();
} catch (RuntimeException error) {
permits.release();
throw error;
}
String requestId = MDC.get("requestId");
FutureTask<T> task =
new FutureTask<>(
() -> {
ForkDeadline.bind(deadline);
if (requestId != null) MDC.put("requestId", requestId);
try {
deadline.check();
return action.apply(deadline);
} finally {
deadline.closeResources();
ForkDeadline.unbind();
MDC.remove("requestId");
}
});
active.add(task);
try {
workers.execute(
() -> {
try {
task.run();
} finally {
active.remove(task);
permits.release();
}
});
} catch (RejectedExecutionException error) {
active.remove(task);
permits.release();
throw new BusinessException(503, "FORK_UNAVAILABLE", "Fork 正在停止,请稍后重试");
}
try {
return task.get(deadline.remaining().toNanos(), TimeUnit.NANOSECONDS);
} catch (TimeoutException error) {
deadline.cancel("FORK_TIMEOUT");
task.cancel(true);
throw failure(deadline);
} catch (InterruptedException error) {
deadline.cancel("FORK_CANCELLED");
task.cancel(true);
Thread.currentThread().interrupt();
throw failure(deadline);
} catch (CancellationException error) {
throw failure(deadline);
} catch (BusinessException error) {
deadline.cancel("FORK_TIMEOUT");
task.cancel(true);
throw failure(deadline);
} catch (ExecutionException error) {
if (error.getCause() instanceof RuntimeException cause) throw cause;
throw new BusinessException(500, "FORK_COPY_FAILED", "Fork 复制失败", deadline.details());
}
}
private BusinessException failure(ForkDeadline deadline) {
BusinessException error = deadline.failure();
return new BusinessException(
error.status(), error.code(), error.getMessage(), deadline.details());
}
@PreDestroy
public void close() {
active.forEach(task -> task.cancel(true));
workers.shutdownNow();
}
}
@@ -0,0 +1,188 @@
package com.linkerbot.vibemake.service.fork;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.config.ForkProperties;
import com.linkerbot.vibemake.service.gitea.GiteaFailure;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/** 不执行 Shell,不记录参数或原始输出;输出与磁盘占用均有上限。 */
@Component
public class GitCommandRunner {
private static final Logger log = LoggerFactory.getLogger(GitCommandRunner.class);
private static final int MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
private final ForkProperties properties;
public GitCommandRunner(ForkProperties properties) { this.properties = properties; }
public record Result(int exitCode, String output, boolean rejected) {}
public Result run(Path workspace, ForkDeadline deadline, String stage, Map<String, String> configuration,
Map<String, String> identity, String... arguments) {
deadline.check();
List<String> command = new ArrayList<>();
command.add(properties.getGitExecutable());
if (workspace != null) command.add("--git-dir=" + workspace);
command.addAll(List.of(arguments));
ProcessBuilder builder = new ProcessBuilder(command);
Map<String, String> environment = builder.environment();
Map<String, String> inherited = new HashMap<>(environment);
environment.clear();
for (String key : List.of("PATH", "SystemRoot", "TMPDIR", "TEMP", "TMP"))
if (inherited.containsKey(key)) environment.put(key, inherited.get(key));
environment.put("LC_ALL", "C.UTF-8");
environment.put("GIT_CONFIG_NOSYSTEM", "1");
environment.put("GIT_CONFIG_GLOBAL", "/dev/null");
environment.put("GIT_ATTR_NOSYSTEM", "1");
environment.put("GIT_TERMINAL_PROMPT", "0");
environment.put("GIT_LFS_SKIP_SMUDGE", "1");
Map<String, String> settings = new LinkedHashMap<>();
settings.put("core.hooksPath", "/dev/null");
settings.put("credential.helper", "");
settings.put("http.followRedirects", "false");
settings.put("protocol.allow", "never");
settings.put("protocol.http.allow", "always");
settings.put("protocol.https.allow", "always");
settings.putAll(configuration);
environment.put("GIT_CONFIG_COUNT", Integer.toString(settings.size()));
int index = 0;
for (Map.Entry<String, String> setting : settings.entrySet()) {
environment.put("GIT_CONFIG_KEY_" + index, setting.getKey());
environment.put("GIT_CONFIG_VALUE_" + index, setting.getValue());
index++;
}
environment.putAll(identity);
Process process = null;
Set<ProcessHandle> children = new HashSet<>();
Thread reader = null;
Thread errorReader = null;
AtomicBoolean overflow = new AtomicBoolean();
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream errors = new ByteArrayOutputStream();
long started = System.nanoTime();
try {
process = builder.start();
process.getOutputStream().close();
InputStream stdout = process.getInputStream();
reader = Thread.ofVirtual().start(() -> drain(stdout, output, overflow, MAX_OUTPUT_BYTES));
InputStream stderr = process.getErrorStream();
errorReader = Thread.ofVirtual().start(() -> drain(stderr, errors, new AtomicBoolean(), 32768));
long checked = 0;
while (true) {
process.descendants().forEach(children::add);
deadline.check();
if (overflow.get()) throw resourceLimit();
if (workspace != null && System.nanoTime() - checked >= TimeUnit.MILLISECONDS.toNanos(250)) {
checkDisk(workspace);
checked = System.nanoTime();
}
if (process.waitFor(50, TimeUnit.MILLISECONDS)) break;
}
while (reader.isAlive()) { reader.join(50); deadline.check(); }
while (errorReader.isAlive()) { errorReader.join(50); deadline.check(); }
deadline.check();
if (overflow.get()) throw resourceLimit();
if (workspace != null) checkDisk(workspace);
int exitCode = process.exitValue();
String diagnostic = errors.toString(StandardCharsets.UTF_8).toLowerCase(Locale.ROOT);
boolean rejected = exitCode != 0 && (diagnostic.contains("authentication failed")
|| diagnostic.contains("could not read username") || diagnostic.contains("[remote rejected]")
|| diagnostic.contains("requested url returned error: 401") || diagnostic.contains("requested url returned error: 403")
|| diagnostic.contains("requested url returned error: 404"));
log.info("Fork Git 阶段完成 projectCode={} stage={} exitCode={} failureType={} durationMs={}",
deadline.projectCode(), stage, exitCode, rejected ? "REMOTE_REJECTED" : exitCode == 0 ? "NONE" : "EXIT_FAILURE",
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started));
return new Result(exitCode, output.toString(StandardCharsets.UTF_8).trim(), rejected);
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
deadline.check();
throw deadline.failure();
} catch (IOException error) {
log.warn("Fork Git 进程异常 projectCode={} stage={} errorType={}", deadline.projectCode(), stage, error.getClass().getSimpleName());
throw failed(deadline);
} finally {
if (process != null) stop(process, children);
boolean interrupted = Thread.interrupted();
for (Thread drain : new Thread[] {reader, errorReader}) {
while (drain != null && drain.isAlive()) {
try { drain.join(); }
catch (InterruptedException error) { interrupted = true; }
}
}
if (interrupted) Thread.currentThread().interrupt();
}
}
private void drain(InputStream source, ByteArrayOutputStream target, AtomicBoolean overflow, int limit) {
try (InputStream input = source) {
byte[] buffer = new byte[8192];
int count;
while ((count = input.read(buffer)) != -1) {
if (count > limit - target.size()) overflow.set(true);
if (!overflow.get()) target.write(buffer, 0, count);
}
} catch (IOException ignored) {
// 进程被终止时管道会关闭;最终由退出状态和截止时间判断结果。
}
}
private void stop(Process process, Set<ProcessHandle> descendants) {
boolean interrupted = Thread.interrupted();
process.descendants().forEach(descendants::add);
descendants.forEach(child -> { if (child.isAlive()) child.destroyForcibly(); });
try {
// 先让父进程回收子进程,再终止仍未退出的父进程,避免遗留僵尸。
try { if (!descendants.isEmpty()) process.waitFor(1, TimeUnit.SECONDS); }
catch (InterruptedException error) { interrupted = true; }
if (process.isAlive()) process.destroyForcibly();
while (process.isAlive()) {
try { process.waitFor(100, TimeUnit.MILLISECONDS); }
catch (InterruptedException error) { interrupted = true; }
}
for (ProcessHandle child : descendants) {
while (child.isAlive()) {
try { child.onExit().get(100, TimeUnit.MILLISECONDS); }
catch (InterruptedException error) { interrupted = true; }
catch (java.util.concurrent.ExecutionException | java.util.concurrent.TimeoutException ignored) { child.destroyForcibly(); }
}
}
} finally {
if (interrupted) Thread.currentThread().interrupt();
}
}
public void checkDisk(Path workspace) throws IOException {
long[] bytes = {0};
Files.walkFileTree(workspace, new SimpleFileVisitor<>() {
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
long size = attributes.size();
if (size > properties.getMaxTemporaryBytes() - bytes[0]) throw resourceLimit();
bytes[0] += size;
return FileVisitResult.CONTINUE;
}
@Override public FileVisitResult visitFileFailed(Path file, IOException error) throws IOException {
if (error instanceof NoSuchFileException) return FileVisitResult.CONTINUE;
throw error;
}
});
}
private BusinessException resourceLimit() {
return new BusinessException(413, "FORK_RESOURCE_LIMIT", "Fork 临时磁盘或元数据超过限制");
}
static BusinessException failed(ForkDeadline deadline) {
if (deadline.writing()) return new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "Fork 写入结果待核对,请先查看工作区", true);
return new BusinessException(502, "FORK_COPY_FAILED", "Fork 快照或 LFS 复制失败,请通过 requestId 排查");
}
}
@@ -0,0 +1,16 @@
package com.linkerbot.vibemake.service.fork;
import com.linkerbot.vibemake.service.gitea.GiteaClient.Repository;
/** 仓库传输边界;准备阶段不创建远端仓库,业务测试可使用内存替身。 */
public interface GitSnapshotCopier {
void checkAvailable();
PreparedSnapshot prepare(Repository source, String publishedSha, String authorName, String authorCode,
ForkDeadline deadline);
interface PreparedSnapshot extends AutoCloseable {
String push(Repository target);
@Override void close();
}
}
@@ -0,0 +1,165 @@
package com.linkerbot.vibemake.service.fork;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
/** git-lfs 自身不支持禁止重定向;在任务内约束所有 batch/action 请求到配置中的 Gitea。 */
final class LfsEndpointGuard implements AutoCloseable {
private static final int MAX_METADATA = 8 * 1024 * 1024;
private final URI trustedBase;
private final URI endpoint;
private final String authorization;
private final String localAuthorization = "Bearer " + UUID.randomUUID();
private final ForkDeadline deadline;
private final ObjectMapper json;
private final HttpServer server;
private final HttpClient http;
private final ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor();
private final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(Thread.ofVirtual().factory());
private final Map<String, Action> actions = new ConcurrentHashMap<>();
private final Set<HttpExchange> exchanges = ConcurrentHashMap.newKeySet();
private final Set<InputStream> responses = ConcurrentHashMap.newKeySet();
private final AtomicBoolean closed = new AtomicBoolean();
private record Action(URI url, Map<String, String> headers) {}
LfsEndpointGuard(URI trustedBase, URI endpoint, String authorization, ForkDeadline deadline, ObjectMapper json) throws IOException {
this.trustedBase = trustedBase;
this.endpoint = endpoint;
this.authorization = authorization;
this.deadline = deadline;
this.json = json;
if (!allowed(endpoint)) throw new IOException("LFS endpoint rejected");
http = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).connectTimeout(deadline.remaining()).build();
try { server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); }
catch (IOException error) { http.shutdownNow(); throw error; }
try {
server.setExecutor(workers);
server.createContext("/lfs", this::handle);
server.start();
timer.schedule(this::close, deadline.remaining().toNanos(), TimeUnit.NANOSECONDS);
} catch (RuntimeException error) { close(); throw error; }
}
String endpoint() { return "http://127.0.0.1:" + server.getAddress().getPort() + "/lfs"; }
String localAuthorization() { return localAuthorization; }
private boolean allowed(URI uri) {
return uri.getRawUserInfo() == null && uri.getRawFragment() == null
&& trustedBase.getScheme().equalsIgnoreCase(uri.getScheme())
&& trustedBase.getRawAuthority().equalsIgnoreCase(uri.getRawAuthority())
&& uri.normalize().getRawPath().startsWith(trustedBase.getRawPath().replaceAll("/+$", "") + "/");
}
private void handle(HttpExchange exchange) {
exchanges.add(exchange);
try (HttpExchange request = exchange) {
deadline.check();
String supplied = request.getRequestHeaders().getFirst("Authorization");
if (supplied == null || !MessageDigest.isEqual(supplied.getBytes(StandardCharsets.UTF_8), localAuthorization.getBytes(StandardCharsets.UTF_8))) {
request.sendResponseHeaders(403, -1);
return;
}
String path = request.getRequestURI().getPath();
boolean batch = path.equals("/lfs/objects/batch") && request.getRequestMethod().equals("POST");
Action action = batch ? new Action(URI.create(endpoint + "/objects/batch"), Map.of()) : actions.get(path);
if (action == null || !Set.of("GET", "POST", "PUT").contains(request.getRequestMethod())) {
request.sendResponseHeaders(400, -1);
return;
}
HttpRequest.Builder outbound = HttpRequest.newBuilder(action.url()).timeout(deadline.remaining())
.header("Authorization", authorization);
if (batch) outbound.header("Accept", "application/vnd.git-lfs+json");
action.headers().forEach(outbound::setHeader);
String type = request.getRequestHeaders().getFirst("Content-Type");
if (type != null) outbound.setHeader("Content-Type", type);
HttpRequest.BodyPublisher body = batch ? HttpRequest.BodyPublishers.ofByteArray(metadata(request.getRequestBody()))
: request.getRequestMethod().equals("GET") ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofInputStream(request::getRequestBody);
outbound.method(request.getRequestMethod(), body);
HttpResponse<InputStream> response = http.send(outbound.build(), HttpResponse.BodyHandlers.ofInputStream());
InputStream stream = response.body();
responses.add(stream);
try (InputStream input = stream) {
// 不把 Location 传给 git-lfs,禁止它自行追随重定向。
if (response.statusCode() < 200 || response.statusCode() >= 300) {
request.sendResponseHeaders(response.statusCode() >= 300 && response.statusCode() < 400 ? 502 : response.statusCode(), -1);
return;
}
if (batch) {
JsonNode result = json.readTree(metadata(input));
for (JsonNode object : result.path("objects")) {
JsonNode entries = object.path("actions");
for (JsonNode value : entries) {
if (!(value instanceof ObjectNode item)) throw new IOException("LFS action rejected");
URI destination = URI.create(item.path("href").asText());
if (!allowed(destination)) throw new IOException("LFS action origin rejected");
Map<String, String> headers = new java.util.HashMap<>();
JsonNode header = item.path("header");
header.fields().forEachRemaining(field -> {
if (Set.of("authorization", "content-type", "accept").contains(field.getKey().toLowerCase(java.util.Locale.ROOT)))
headers.put(field.getKey(), field.getValue().asText());
});
String route = "/lfs/action/" + UUID.randomUUID();
actions.put(route, new Action(destination, headers));
item.put("href", endpoint().replace("/lfs", "") + route);
item.putObject("header").put("Authorization", localAuthorization);
}
}
byte[] bytes = json.writeValueAsBytes(result);
request.getResponseHeaders().set("Content-Type", "application/vnd.git-lfs+json");
request.sendResponseHeaders(response.statusCode(), bytes.length);
request.getResponseBody().write(bytes);
} else {
request.sendResponseHeaders(response.statusCode(), 0);
byte[] buffer = new byte[65536];
int count;
while ((count = input.read(buffer)) != -1) {
deadline.check();
request.getResponseBody().write(buffer, 0, count);
}
}
} finally { responses.remove(stream); }
} catch (IOException | InterruptedException | RuntimeException error) {
if (error instanceof InterruptedException) Thread.currentThread().interrupt();
// 不输出服务端原始响应、地址、头或凭据;git-lfs 会以非零状态结束该阶段。
exchange.close();
} finally { exchanges.remove(exchange); }
}
private byte[] metadata(InputStream input) throws IOException {
byte[] bytes = input.readNBytes(MAX_METADATA + 1);
if (bytes.length > MAX_METADATA) throw new IOException("LFS metadata limit exceeded");
return bytes;
}
@Override public void close() {
if (closed.compareAndSet(false, true)) {
server.stop(0);
exchanges.forEach(HttpExchange::close);
responses.forEach(stream -> { try { stream.close(); } catch (IOException ignored) {} });
http.shutdownNow();
workers.shutdownNow();
timer.shutdownNow();
actions.clear();
}
// 并发名额只能在转发流也实际退出后释放;不能只停止命令行进程。
workers.close();
}
}
@@ -0,0 +1,71 @@
package com.linkerbot.vibemake.service.gitea;
import com.linkerbot.vibemake.bean.Contracts.*;
import com.linkerbot.vibemake.common.PageResponse;
import java.util.List;
import java.time.Duration;
public interface GiteaClient {
default String authenticatedUsername() { throw new UnsupportedOperationException("未实现服务账号查询"); }
record Repository(long id, String owner, String name) {}
record StoredFile(String path, String blobSha, byte[] bytes) {}
record Change(String operation, String path, String blobSha, byte[] bytes) {}
record RemoteRepository(long id, String owner, String name, boolean privateRepo,
boolean mirror, boolean empty, String originalUrl, String defaultBranch) {
public Repository repository() { return new Repository(id, owner, name); }
}
default RemoteRepository migrate(String cloneUrl, String name, Duration timeout) {
throw new UnsupportedOperationException("未实现迁移");
}
default RemoteRepository migrate(String cloneUrl, String name, Duration timeout, String description) {
throw new UnsupportedOperationException("未实现带任务标识的迁移");
}
record MigrationTarget(RemoteRepository repository, String description) {}
default MigrationTarget inspectMigrationTarget(String name) {
throw new UnsupportedOperationException("未实现失败迁移仓库核验");
}
default void deleteRepository(Repository repository) {
throw new UnsupportedOperationException("未实现仓库删除");
}
default RemoteRepository inspect(String name) { throw new UnsupportedOperationException("未实现仓库检查"); }
default String branch(Repository repository, String branch) { throw new UnsupportedOperationException("未实现分支检查"); }
default void createBranch(Repository repository, String name, String sha) { throw new UnsupportedOperationException("未实现分支创建"); }
default void defaultBranch(Repository repository, String name) { throw new UnsupportedOperationException("未实现默认分支设置"); }
default void checkMigrationSettings() { throw new UnsupportedOperationException("未实现迁移能力检查"); }
default List<String> migrationWarnings(Repository repository, String sha, long maxFileBytes) {
return List.of("在线下载仍受单文件限制,LFS 实体在线读取能力未扩展;Git 快照 Fork 保留子模块引用,不递归复制依赖");
}
Repository createRepository(String name, boolean initialize);
String head(Repository repository);
List<TreeEntry> tree(Repository repository, String sha, String path);
StoredFile file(Repository repository, String sha, String path);
CommitView commit(
Repository repository,
List<Change> changes,
String message,
String authorName,
String authorCode);
PageResponse<HistoryEntry> history(Repository repository, long page, long size);
}
@@ -0,0 +1,16 @@
package com.linkerbot.vibemake.service.gitea;
import com.linkerbot.vibemake.common.BusinessException;
public class GiteaFailure extends BusinessException {
private final boolean uncertain;
public GiteaFailure(int status, String code, String message, boolean uncertain) {
super(status, code, message);
this.uncertain = uncertain;
}
public boolean uncertain() {
return uncertain;
}
}
@@ -0,0 +1,439 @@
package com.linkerbot.vibemake.service.gitea;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.bean.Contracts.*;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.common.FilePaths;
import com.linkerbot.vibemake.common.LimitedHttpBody;
import com.linkerbot.vibemake.common.PageResponse;
import com.linkerbot.vibemake.service.config.VibemakeProperties;
import com.linkerbot.vibemake.service.fork.ForkDeadline;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.*;
@Component
public class RestGiteaClient implements GiteaClient {
private final VibemakeProperties properties;
private final ObjectMapper json;
private final HttpClient http;
public RestGiteaClient(VibemakeProperties properties, ObjectMapper json) {
this.properties = properties;
this.json = json;
this.http =
HttpClient.newBuilder()
.connectTimeout(properties.getGitea().getConnectTimeout())
.followRedirects(HttpClient.Redirect.NEVER)
.build();
}
private static String encode(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
}
private String repoPath(Repository repo) {
return "/repos/" + encode(repo.owner()) + "/" + encode(repo.name());
}
private String filePath(String path) {
return Arrays.stream(path.split("/"))
.map(RestGiteaClient::encode)
.reduce((a, b) -> a + "/" + b)
.orElse("");
}
private HttpResponse<byte[]> request(String method, String path, Object body) {
return request(method, path, body, properties.getGitea().getRequestTimeout());
}
private HttpResponse<byte[]> request(
String method, String path, Object body, Duration timeout) {
if (properties.getGitea().getToken().isBlank())
throw new GiteaFailure(503, "GITEA_NOT_CONFIGURED", "请配置 Gitea Token", false);
try {
String base = properties.getGitea().getBaseUrl().replaceAll("/+$", "");
HttpRequest.Builder builder =
HttpRequest.newBuilder(URI.create(base + "/api/v1" + path))
.timeout(ForkDeadline.bounded(timeout))
.header("Accept", "application/json")
.header("Authorization", "token " + properties.getGitea().getToken());
if (body == null) builder.method(method, HttpRequest.BodyPublishers.noBody());
else
builder.header("Content-Type", "application/json")
.method(
method,
HttpRequest.BodyPublishers.ofByteArray(
json.writeValueAsBytes(body)));
HttpResponse<byte[]> response =
http.send(
builder.build(),
info -> new LimitedHttpBody(responseLimit(path, info.statusCode())));
int status = response.statusCode();
if (status < 200 || status >= 300) {
if (status == 404) throw new GiteaFailure(404, "NOT_FOUND", "仓库文件或版本不存在", false);
if (status == 422 && path.equals("/repos/migrate"))
throw new GiteaFailure(
422, "GITEA_MIGRATION_REJECTED", "Gitea 迁移失败,需核对源站访问和服务端迁移日志", false);
if (status == 409 || status == 422)
throw new GiteaFailure(409, "GITEA_CONFLICT", "仓库内容冲突,请刷新后重试", false);
throw new GiteaFailure(
502,
"GITEA_ERROR",
"仓库服务返回异常,请通过 requestId 排查",
!method.equals("GET") && status >= 500);
}
return response;
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw new GiteaFailure(
504, "REMOTE_RESULT_UNKNOWN", "仓库调用被中断,写入结果需核对", !method.equals("GET"));
} catch (IOException error) {
for (Throwable cause = error; cause != null; cause = cause.getCause())
if (cause instanceof LimitedHttpBody.TooLarge && method.equals("GET"))
throw new GiteaFailure(502, "GITEA_RESPONSE_TOO_LARGE", "仓库响应超过读取限制", false);
throw new GiteaFailure(
504, "REMOTE_RESULT_UNKNOWN", "仓库连接异常或超时,写入结果需核对", !method.equals("GET"));
}
}
private long responseLimit(String path, int status) {
if (status < 200 || status >= 300) return 64 * 1024;
if (path.contains("/raw/")) return properties.getMaxFileBytes();
if (path.contains("/contents"))
return (properties.getMaxFileBytes() + 2) / 3 * 4 + 2 * 1024 * 1024;
return 8 * 1024 * 1024;
}
private JsonNode parse(byte[] bytes, boolean writing) {
try {
return json.readTree(bytes);
} catch (IOException error) {
throw new GiteaFailure(502, "GITEA_INVALID_RESPONSE", "仓库响应格式异常", writing);
}
}
@Override
public String authenticatedUsername() {
JsonNode user = parse(request("GET", "/user", null).body(), false);
if (!user.path("login").isTextual() || user.path("login").asText().isBlank())
throw new GiteaFailure(502, "FORK_COPY_FAILED", "无法确认 Gitea 服务账号身份", false);
return user.path("login").asText();
}
@Override
public Repository createRepository(String name, boolean initialize) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("name", name);
body.put("private", true);
body.put("auto_init", initialize);
body.put("default_branch", "main");
if (initialize) body.put("readme", "Default");
String owner = properties.getGitea().getOwner();
JsonNode data =
parse(request("POST", "/orgs/" + encode(owner) + "/repos", body).body(), true);
if (data.path("id").asLong() <= 0 || !data.path("private").asBoolean())
throw new GiteaFailure(502, "GITEA_INVALID_RESPONSE", "仓库创建结果异常,需人工核对", true);
return new Repository(data.path("id").asLong(), owner, name);
}
@Override
public String head(Repository repo) {
return branch(repo, "main");
}
@Override
public String branch(Repository repo, String branchName) {
JsonNode branch =
parse(
request("GET", repoPath(repo) + "/branches/" + encode(branchName), null)
.body(),
false);
return FilePaths.sha(branch.path("commit").path("id").asText());
}
private RemoteRepository remote(JsonNode data) {
if (data.path("id").asLong() <= 0)
throw new GiteaFailure(502, "GITEA_INVALID_RESPONSE", "仓库响应缺少标识", true);
return new RemoteRepository(
data.path("id").asLong(),
data.path("owner").path("login").asText(),
data.path("name").asText(),
data.path("private").asBoolean(),
data.path("mirror").asBoolean(),
data.path("empty").asBoolean(),
data.path("original_url").asText(),
data.path("default_branch").asText());
}
@Override
public RemoteRepository migrate(String cloneUrl, String name, Duration timeout) {
return migrate(cloneUrl, name, timeout, null);
}
@Override
public RemoteRepository migrate(
String cloneUrl, String name, Duration timeout, String description) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("clone_addr", cloneUrl);
body.put("repo_owner", properties.getGitea().getOwner());
body.put("repo_name", name);
body.put("service", "git");
body.put("private", true);
body.put("mirror", false);
body.put("lfs", true);
if (description != null) body.put("description", description);
for (String option :
List.of("issues", "labels", "milestones", "pull_requests", "releases", "wiki"))
body.put(option, false);
HttpResponse<byte[]> response = request("POST", "/repos/migrate", body, timeout);
if (response.statusCode() != 201)
throw new GiteaFailure(502, "MIGRATION_NOT_CONFIRMED", "迁移没有返回已完成的 201 收据,需人工核对", true);
return remote(parse(response.body(), true));
}
@Override
public RemoteRepository inspect(String name) {
return remote(
parse(
request(
"GET",
"/repos/"
+ encode(properties.getGitea().getOwner())
+ "/"
+ encode(name),
null)
.body(),
false));
}
@Override
public MigrationTarget inspectMigrationTarget(String name) {
JsonNode data =
parse(
request(
"GET",
"/repos/"
+ encode(properties.getGitea().getOwner())
+ "/"
+ encode(name),
null)
.body(),
false);
if (!data.path("private").isBoolean() || !data.path("mirror").isBoolean())
throw new GiteaFailure(502, "GITEA_INVALID_RESPONSE", "无法核验迁移仓库属性", false);
return new MigrationTarget(remote(data), data.path("description").asText(null));
}
@Override
public void deleteRepository(Repository repository) {
if (!properties.getGitea().getOwner().equals(repository.owner()))
throw BusinessException.conflict("仓库组织与当前配置不一致,禁止删除");
RemoteRepository current = inspect(repository.name());
if (current.id() != repository.id()) throw BusinessException.conflict("仓库身份已变化,禁止删除");
HttpResponse<byte[]> response = request("DELETE", repoPath(repository), null);
if (response.statusCode() != 204)
throw new GiteaFailure(502, "MIGRATION_CLEANUP_UNCONFIRMED", "仓库清理结果尚未确认", true);
}
@Override
public void createBranch(Repository repo, String name, String sha) {
request(
"POST",
repoPath(repo) + "/branches",
Map.of("new_branch_name", name, "old_ref_name", FilePaths.sha(sha)));
}
@Override
public void defaultBranch(Repository repo, String name) {
request("PATCH", repoPath(repo), Map.of("default_branch", name));
}
@Override
public void checkMigrationSettings() {
JsonNode settings = parse(request("GET", "/settings/repository", null).body(), false);
if (!settings.has("lfs_disabled")
|| settings.path("lfs_disabled").asBoolean()
|| settings.path("migrations_disabled").asBoolean()
|| settings.path("http_git_disabled").asBoolean())
throw BusinessException.badRequest("Gitea 必须启用迁移、HTTP Git 和 LFS");
}
@Override
public List<String> migrationWarnings(Repository repo, String sha, long maxFileBytes) {
List<String> warnings = new ArrayList<>();
warnings.add("已请求迁移 LFS;在线 API 的 LFS 实体读取能力未扩展,Git 快照 Fork 会复制发布版本引用的实体");
long large = 0;
long links = 0;
long modules = 0;
long seen = 0;
for (int page = 1; page <= 10000; page++) {
JsonNode tree =
parse(
request(
"GET",
repoPath(repo)
+ "/git/trees/"
+ FilePaths.sha(sha)
+ "?recursive=true&per_page=1000&page="
+ page,
null)
.body(),
false);
JsonNode entries = tree.path("tree");
if (!entries.isArray())
throw new GiteaFailure(502, "GITEA_INVALID_RESPONSE", "Git 文件树响应格式异常", false);
for (JsonNode entry : entries) {
if (entry.path("size").asLong() > maxFileBytes) large++;
if (entry.path("mode").asText().equals("120000")) links++;
if (entry.path("mode").asText().equals("160000")) modules++;
}
seen += entries.size();
if (seen >= tree.path("total_count").asLong(seen)
&& !tree.path("truncated").asBoolean()) break;
if (entries.isEmpty() || page == 10000) {
warnings.add("文件树扫描不完整,需要人工核对剩余文件");
break;
}
}
if (large > 0) warnings.add("发布快照有 " + large + " 个文件超过社区单文件读取限制 " + maxFileBytes + " 字节");
if (links > 0) warnings.add("发布快照有 " + links + " 个符号链接,在线普通文件读取不支持,Git 快照 Fork 保留链接");
if (modules > 0) warnings.add("发布快照有 " + modules + " 个子模块引用,Git 快照 Fork 保留引用,不递归复制依赖仓库");
return List.copyOf(warnings);
}
private JsonNode contents(Repository repo, String sha, String path) {
String suffix = path.isEmpty() ? "" : "/" + filePath(path);
return parse(
request(
"GET",
repoPath(repo)
+ "/contents"
+ suffix
+ "?ref="
+ FilePaths.sha(sha),
null)
.body(),
false);
}
@Override
public List<TreeEntry> tree(Repository repo, String sha, String path) {
JsonNode nodes = contents(repo, sha, FilePaths.directory(path));
if (!nodes.isArray()) throw BusinessException.badRequest("路径不是目录");
List<TreeEntry> result = new ArrayList<>();
for (JsonNode node : nodes)
result.add(
new TreeEntry(
node.path("path").asText(),
node.path("name").asText(),
node.path("type").asText(),
node.path("size").asLong(),
node.path("sha").asText()));
result.sort(
Comparator.comparing((TreeEntry entry) -> !entry.type().equals("dir"))
.thenComparing(TreeEntry::name));
return result;
}
@Override
public StoredFile file(Repository repo, String sha, String path) {
FilePaths.file(path);
JsonNode node = contents(repo, sha, path);
if (!node.isObject() || !node.path("type").asText().equals("file"))
throw BusinessException.badRequest("仅支持普通文件,不支持符号链接或子模块");
if (node.path("size").asLong() > properties.getMaxFileBytes())
throw new BusinessException(413, "FILE_TOO_LARGE", "文件超过读取限制");
byte[] bytes;
try {
if (node.path("encoding").asText().equals("base64") && node.hasNonNull("content"))
bytes = Base64.getMimeDecoder().decode(node.path("content").asText());
else
bytes =
request(
"GET",
repoPath(repo) + "/raw/" + filePath(path) + "?ref=" + sha,
null)
.body();
} catch (IllegalArgumentException error) {
throw new GiteaFailure(502, "GITEA_INVALID_RESPONSE", "仓库文件编码异常", false);
}
if (bytes.length > properties.getMaxFileBytes())
throw new BusinessException(413, "FILE_TOO_LARGE", "文件超过读取限制");
return new StoredFile(path, node.path("sha").asText(), bytes);
}
@Override
public CommitView commit(
Repository repo,
List<Change> changes,
String message,
String authorName,
String authorCode) {
List<Map<String, Object>> files = new ArrayList<>();
for (Change change : changes) {
Map<String, Object> item = new LinkedHashMap<>();
item.put("operation", change.operation());
item.put("path", FilePaths.file(change.path()));
if (change.blobSha() != null) item.put("sha", change.blobSha());
if (!change.operation().equals("delete"))
item.put("content", Base64.getEncoder().encodeToString(change.bytes()));
files.add(item);
}
Map<String, Object> body =
Map.of(
"branch",
"main",
"files",
files,
"message",
message,
"author",
Map.of(
"name",
authorName,
"email",
authorCode + "@users.vibemake.invalid"));
JsonNode result = parse(request("POST", repoPath(repo) + "/contents", body).body(), true);
String sha = result.path("commit").path("sha").asText();
if (sha.isBlank())
throw new GiteaFailure(502, "GITEA_INVALID_RESPONSE", "仓库未返回提交版本,需人工核对", true);
return new CommitView(FilePaths.sha(sha), message);
}
@Override
public PageResponse<HistoryEntry> history(Repository repo, long page, long size) {
HttpResponse<byte[]> response =
request(
"GET",
repoPath(repo) + "/commits?sha=main&page=" + page + "&limit=" + size,
null);
JsonNode data = parse(response.body(), false);
List<HistoryEntry> items = new ArrayList<>();
for (JsonNode node : data) {
JsonNode commit = node.path("commit");
items.add(
new HistoryEntry(
node.path("sha").asText(),
commit.path("message").asText(),
commit.path("author").path("name").asText(),
commit.path("author").path("date").asText()));
}
long total =
response.headers()
.firstValue("X-Total-Count")
.map(Long::parseLong)
.orElse((long) items.size());
return new PageResponse<>(items, page, size, total);
}
}
@@ -0,0 +1,299 @@
package com.linkerbot.vibemake.service.impl;
import com.linkerbot.vibemake.bean.ai.AiContracts.*;
import com.linkerbot.vibemake.common.ApiResponse;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.AiSearchService;
import com.linkerbot.vibemake.service.ai.AiProjectAssistant;
import com.linkerbot.vibemake.service.config.AiProperties;
import com.linkerbot.vibemake.service.config.ForkProperties;
import com.linkerbot.vibemake.service.state.RateLimits;
import jakarta.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
/** Redis 用户频率限制与本机 SSE 生命周期。 */
@Service
public class AiSearchServiceImpl implements AiSearchService {
private static final Logger log = LoggerFactory.getLogger(AiSearchServiceImpl.class);
private final AiProperties properties;
private final AiProjectAssistant assistant;
private final ForkProperties forkProperties;
private final Semaphore permits;
private final ExecutorService workers =
Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name("ai-search-", 0).factory());
private final ScheduledExecutorService timer =
Executors.newScheduledThreadPool(
2, Thread.ofPlatform().daemon(true).name("ai-search-timer-", 0).factory());
private final RateLimits rates;
private final Set<Job> active = ConcurrentHashMap.newKeySet();
public AiSearchServiceImpl(
AiProperties properties,
AiProjectAssistant assistant,
ForkProperties forkProperties,
RateLimits rates) {
this.properties = properties;
this.assistant = assistant;
this.forkProperties = forkProperties;
this.rates = rates;
permits = new Semaphore(properties.getMaxConcurrent());
}
@Override
public SseEmitter chat(long userId, ChatRequest request) {
validateHistory(request);
if (!properties.isEnabled())
throw new BusinessException(503, "AI_UNAVAILABLE", "Maker AI 暂未开启");
if (!permits.tryAcquire())
throw new com.linkerbot.vibemake.common.RateLimitedException(
"AI_BUSY", "Maker AI 繁忙,请稍后重试", 1);
try {
rateLimit(userId);
} catch (RuntimeException error) {
permits.release();
throw error;
}
Job job = new Job(userId, request, MDC.get("requestId"));
active.add(job);
try {
job.start();
return job.emitter;
} catch (RejectedExecutionException error) {
job.cancel();
job.release();
throw new BusinessException(503, "AI_UNAVAILABLE", "Maker AI 暂不可用");
}
}
private void validateHistory(ChatRequest request) {
if (request.history().size() % 2 != 0)
throw BusinessException.badRequest("history 必须为完整的用户和助手对话轮次");
for (int index = 0; index < request.history().size(); index++) {
String expected = index % 2 == 0 ? "user" : "assistant";
if (!expected.equals(request.history().get(index).role()))
throw BusinessException.badRequest("history 必须由 user 和 assistant 交替组成");
}
}
private void rateLimit(long userId) {
rates.check(
"ai",
Long.toString(userId),
properties.getRequestsPerMinute(),
Duration.ofMinutes(1),
"AI_RATE_LIMITED",
"Maker AI 请求过于频繁,请稍后重试");
}
@PreDestroy
public void close() {
active.forEach(Job::cancel);
workers.shutdownNow();
timer.shutdownNow();
}
private final class Job {
private final long userId;
private final ChatRequest request;
private final String requestId;
private final long started = System.nanoTime();
private final SseEmitter emitter =
new SseEmitter(
properties
.getSearchTimeout()
.plus(forkProperties.getTimeout())
.plusSeconds(15)
.toMillis());
private final AtomicBoolean finished = new AtomicBoolean();
private final AtomicBoolean released = new AtomicBoolean();
private final FutureTask<Void> task;
private volatile ScheduledFuture<?> heartbeat;
private volatile ScheduledFuture<?> deadline;
private Job(long userId, ChatRequest request, String requestId) {
this.userId = userId;
this.request = request;
this.requestId = requestId;
task =
new FutureTask<>(
() -> {
run();
return null;
});
emitter.onCompletion(this::cancel);
emitter.onError(ignored -> cancel());
emitter.onTimeout(
() ->
fail(
new BusinessException(
504,
"AI_TIMEOUT",
"Maker AI 处理超时,若涉及创建或 Fork,请先核对工作区项目状态")));
}
private void start() {
heartbeat =
timer.scheduleAtFixedRate(
this::heartbeat,
properties.getHeartbeatInterval().toMillis(),
properties.getHeartbeatInterval().toMillis(),
TimeUnit.MILLISECONDS);
deadline =
timer.schedule(
() ->
fail(
new BusinessException(
504,
"AI_TIMEOUT",
"Maker AI 处理超时,若涉及创建或 Fork,请先核对工作区项目状态")),
properties.getSearchTimeout().toMillis(),
TimeUnit.MILLISECONDS);
workers.execute(
() -> {
try {
task.run();
} finally {
release();
}
});
if (finished.get()) stopTimers();
}
private void run() {
if (requestId != null) MDC.put("requestId", requestId);
try {
log.info("Maker AI 开始 requestId={}", requestId);
ChatResult result =
assistant.chat(userId, request, progress -> send("progress", progress));
if (finished.compareAndSet(false, true)) {
write("result", success(result));
stopTimers();
emitter.complete();
log.info(
"Maker AI 完成 requestId={} status={} resultCount={} projectCode={}"
+ " durationMs={}",
requestId,
result.status(),
result.projects().size(),
result.project() == null ? null : result.project().projectCode(),
elapsed());
}
} catch (BusinessException error) {
fail(error);
} catch (Exception error) {
log.warn(
"Maker AI 异常 requestId={} exceptionType={} location={} durationMs={}",
requestId,
error.getClass().getSimpleName(),
error.getStackTrace().length == 0 ? null : error.getStackTrace()[0],
elapsed());
fail(
new BusinessException(
500, "AI_SEARCH_FAILURE", "Maker AI 处理失败,若涉及创建或 Fork,请先核对工作区项目状态"));
} finally {
stopTimers();
MDC.remove("requestId");
}
}
private void send(String event, Object data) {
if (finished.get() || Thread.currentThread().isInterrupted()) throw cancelled();
if (data instanceof Progress progress && "forking".equals(progress.stage())) {
if (deadline != null) deadline.cancel(false);
deadline =
timer.schedule(
() ->
fail(
new BusinessException(
504,
"FORK_TIMEOUT",
"Fork 超时,请先核对工作区项目状态")),
forkProperties.getTimeout().plusSeconds(15).toMillis(),
TimeUnit.MILLISECONDS);
}
if (!write(event, success(data))) throw cancelled();
}
private ApiResponse<Object> success(Object data) {
return new ApiResponse<>("OK", "成功", data, requestId);
}
private boolean write(String event, ApiResponse<?> data) {
try {
emitter.send(SseEmitter.event().name(event).data(data));
return true;
} catch (IOException | IllegalStateException error) {
cancel();
return false;
}
}
private void heartbeat() {
if (finished.get()) return;
try {
emitter.send(SseEmitter.event().comment("keep-alive"));
} catch (IOException | IllegalStateException error) {
cancel();
}
}
private void fail(BusinessException error) {
if (!finished.compareAndSet(false, true)) return;
log.warn(
"Maker AI 失败 requestId={} code={} durationMs={}",
requestId,
error.code(),
elapsed());
stopTimers();
write(
"error",
new ApiResponse<>(
error.code(), error.getMessage(), error.details(), requestId));
emitter.complete();
task.cancel(true);
}
private void cancel() {
boolean first = finished.compareAndSet(false, true);
stopTimers();
// 即使终态写出时连接断开,也必须停止未完成的工作。
if (first) {
task.cancel(true);
emitter.complete();
log.info("Maker AI 连接关闭 requestId={} durationMs={}", requestId, elapsed());
}
}
private void stopTimers() {
if (heartbeat != null) heartbeat.cancel(false);
if (deadline != null) deadline.cancel(false);
}
private void release() {
if (released.compareAndSet(false, true)) {
active.remove(this);
permits.release();
}
}
private long elapsed() {
return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started);
}
private BusinessException cancelled() {
return new BusinessException(499, "AI_CANCELLED", "Maker AI 已取消");
}
}
}
@@ -0,0 +1,50 @@
package com.linkerbot.vibemake.service.impl;
import com.linkerbot.vibemake.bean.Contracts.CoverUploadInput;
import com.linkerbot.vibemake.bean.Contracts.CoverUploadSignature;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.CoverUploadService;
import com.linkerbot.vibemake.service.UserService;
import com.linkerbot.vibemake.service.config.OssProperties;
import com.linkerbot.vibemake.service.oss.OssPostSigner;
import com.linkerbot.vibemake.service.state.RateLimits;
import com.linkerbot.vibemake.service.support.ProjectActors;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
@RequiredArgsConstructor
public class CoverUploadServiceImpl implements CoverUploadService {
private final RateLimits rateLimits;
private static final Logger log = LoggerFactory.getLogger(CoverUploadServiceImpl.class);
private static final Map<String, String> EXTENSIONS =
Map.of("image/jpeg", "jpg", "image/png", "png", "image/webp", "webp");
private final UserService users;
private final OssProperties properties;
private final OssPostSigner signer;
@Override
public CoverUploadSignature signature(long userId, CoverUploadInput input) {
rateLimits.operation("cover-sign", userId);
if (!properties.isEnabled())
throw new BusinessException(503, "OSS_UNAVAILABLE", "OSS 封面上传暂未开启");
String extension = EXTENSIONS.get(input.contentType());
if (extension == null) throw BusinessException.badRequest("封面仅支持 JPG、PNG、WebP 图片");
if (input.fileSize() > OssPostSigner.MAX_FILE_BYTES)
throw new BusinessException(413, "UPLOAD_TOO_LARGE", "封面图片不能超过 5 MiB");
ProjectActors.Author author = ProjectActors.author(users, userId);
CoverUploadSignature result = signer.sign(author.code(), input.contentType(), extension);
log.info(
"生成封面上传签名 userCode={} objectKey={} expiresAt={}",
author.code(),
result.objectKey(),
result.expiresAt());
return result;
}
}
@@ -0,0 +1,282 @@
package com.linkerbot.vibemake.service.impl;
import com.linkerbot.vibemake.bean.Contracts.*;
import com.linkerbot.vibemake.bean.entity.Project;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.service.FileService;
import com.linkerbot.vibemake.service.ProjectService;
import com.linkerbot.vibemake.service.UserService;
import com.linkerbot.vibemake.service.config.VibemakeProperties;
import com.linkerbot.vibemake.service.gitea.*;
import com.linkerbot.vibemake.service.state.RateLimits;
import com.linkerbot.vibemake.service.support.ProjectActors;
import com.linkerbot.vibemake.service.support.ProjectSupport;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.*;
import java.util.*;
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {
private final RateLimits rateLimits;
private static final Logger log = LoggerFactory.getLogger(FileServiceImpl.class);
private final ProjectService projects;
private final UserService users;
private final GiteaClient gitea;
private final VibemakeProperties config;
@Override
public TreeView ownerTree(long userId, String code, String path, String commitSha) {
Project project = projects.readyOwner(userId, code);
String sha =
commitSha == null
? gitea.head(projects.repository(project))
: FilePaths.sha(commitSha);
return tree(project, sha, path);
}
@Override
public TreeView vibemakeTree(String code, String path) {
Project project = projects.published(code);
return tree(project, project.getPublishedCommitSha(), path);
}
private TreeView tree(Project project, String sha, String path) {
String normalized = FilePaths.directory(path);
return new TreeView(
sha, normalized, gitea.tree(projects.repository(project), sha, normalized));
}
@Override
public GiteaClient.StoredFile ownerFile(
long userId, String code, String path, String commitSha) {
Project project = projects.readyOwner(userId, code);
String sha =
commitSha == null
? gitea.head(projects.repository(project))
: FilePaths.sha(commitSha);
return gitea.file(projects.repository(project), sha, FilePaths.file(path));
}
@Override
public FileView ownerFileView(long userId, String code, String path, String commitSha) {
Project project = projects.readyOwner(userId, code);
String sha =
commitSha == null
? gitea.head(projects.repository(project))
: FilePaths.sha(commitSha);
return fileView(sha, gitea.file(projects.repository(project), sha, FilePaths.file(path)));
}
@Override
public GiteaClient.StoredFile vibemakeFile(String code, String path) {
Project project = projects.published(code);
return gitea.file(
projects.repository(project),
project.getPublishedCommitSha(),
FilePaths.file(path));
}
@Override
public FileView vibemakeFileView(String code, String path) {
Project project = projects.published(code);
return fileView(
project.getPublishedCommitSha(),
gitea.file(
projects.repository(project),
project.getPublishedCommitSha(),
FilePaths.file(path)));
}
private String text(byte[] bytes) {
if (bytes.length > config.getMaxTextBytes()) return null;
for (byte value : bytes) if (value == 0) return null;
try {
return StandardCharsets.UTF_8
.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes))
.toString();
} catch (CharacterCodingException error) {
return null;
}
}
private FileView fileView(String sha, GiteaClient.StoredFile file) {
String content = text(file.bytes());
return new FileView(
sha,
file.path(),
file.blobSha(),
file.bytes().length,
content == null ? "base64" : "utf-8",
content == null ? Base64.getEncoder().encodeToString(file.bytes()) : content,
content != null);
}
private void size(long bytes, long max) {
if (bytes > max) throw new BusinessException(413, "FILE_TOO_LARGE", "文件或请求超过大小限制");
}
private String expected(Project project, String expectedSha) {
String sha = FilePaths.sha(expectedSha);
if (!sha.equals(gitea.head(projects.repository(project))))
throw BusinessException.conflict("工作区版本已变化,请刷新后重新提交");
return sha;
}
@Override
public CommitView commit(long userId, String code, CommitInput input) {
rateLimits.operation("file-write", userId);
return projects.write(
userId,
code,
project -> {
projects.ready(project);
String sha = expected(project, input.expectedCommitSha());
GiteaClient.Repository repo = projects.repository(project);
List<GiteaClient.Change> changes = new ArrayList<>();
Set<String> paths = new HashSet<>();
long bytes = 0;
for (FileChange item : input.changes()) {
String path = FilePaths.file(item.path());
if (item.action() == ChangeAction.CREATE_DIRECTORY) path += "/.gitkeep";
if (!paths.add(path)) throw BusinessException.badRequest("一次提交不能重复修改同一路径");
switch (item.action()) {
case CREATE_FILE, CREATE_DIRECTORY -> {
String content =
item.action() == ChangeAction.CREATE_DIRECTORY
? ""
: item.content();
if (content == null)
throw BusinessException.badRequest("新文件必须提供 content");
byte[] data = content.getBytes(StandardCharsets.UTF_8);
size(data.length, config.getMaxTextBytes());
changes.add(new GiteaClient.Change("create", path, null, data));
bytes += data.length;
size(bytes, config.getMaxRequestBytes());
}
case UPDATE_FILE -> {
if (item.content() == null)
throw BusinessException.badRequest("修改文件必须提供 content");
GiteaClient.StoredFile old = gitea.file(repo, sha, path);
if (text(old.bytes()) == null)
throw BusinessException.badRequest("该文件不支持在线文本编辑,请通过上传替换");
byte[] data = item.content().getBytes(StandardCharsets.UTF_8);
size(data.length, config.getMaxTextBytes());
changes.add(
new GiteaClient.Change(
"update", path, old.blobSha(), data));
bytes += data.length;
size(bytes, config.getMaxRequestBytes());
}
case DELETE_FILE -> {
GiteaClient.StoredFile old = gitea.file(repo, sha, path);
changes.add(
new GiteaClient.Change(
"delete", path, old.blobSha(), null));
}
}
}
size(bytes, config.getMaxRequestBytes());
ProjectActors.Author author = ProjectActors.author(users, userId);
CommitView result =
gitea.commit(
repo,
changes,
input.message(),
author.nickname(),
author.code());
log.info(
"文件提交 projectCode={} commitSha={} fileCount={}",
code,
result.commitSha(),
changes.size());
return result;
});
}
@Override
public CommitView upload(
long userId,
String code,
String expectedSha,
String message,
String directory,
List<MultipartFile> files,
List<String> paths) {
rateLimits.operation("file-write", userId);
if (message == null || message.isBlank() || message.length() > 1000)
throw BusinessException.badRequest("提交说明不合法");
if (files == null
|| files.isEmpty()
|| files.size() > 500
|| (paths != null && paths.size() != files.size()))
throw BusinessException.badRequest("文件和路径数量不合法");
String prefix = FilePaths.directory(directory);
return projects.write(
userId,
code,
project -> {
projects.ready(project);
String sha = expected(project, expectedSha);
GiteaClient.Repository repo = projects.repository(project);
List<GiteaClient.Change> changes = new ArrayList<>();
Set<String> unique = new HashSet<>();
long bytes = 0;
for (int i = 0; i < files.size(); i++) {
MultipartFile file = files.get(i);
String relative =
FilePaths.file(
paths == null ? file.getOriginalFilename() : paths.get(i));
String path =
FilePaths.file(
prefix.isEmpty() ? relative : prefix + "/" + relative);
if (!unique.add(path)) throw BusinessException.badRequest("上传路径不能重复");
size(file.getSize(), config.getMaxFileBytes());
bytes += file.getSize();
size(bytes, config.getMaxRequestBytes());
byte[] data;
try {
data = file.getBytes();
} catch (IOException error) {
throw BusinessException.badRequest("读取上传文件失败");
}
String blob = null;
try {
blob = gitea.file(repo, sha, path).blobSha();
} catch (GiteaFailure missing) {
if (missing.status() != 404) throw missing;
}
changes.add(
new GiteaClient.Change(
blob == null ? "create" : "update", path, blob, data));
}
ProjectActors.Author author = ProjectActors.author(users, userId);
CommitView result =
gitea.commit(repo, changes, message, author.nickname(), author.code());
log.info(
"文件上传 projectCode={} commitSha={} fileCount={}",
code,
result.commitSha(),
changes.size());
return result;
});
}
@Override
public PageResponse<HistoryEntry> history(long userId, String code, long page, long size) {
ProjectSupport.pageCheck(page, size);
return gitea.history(projects.repository(projects.readyOwner(userId, code)), page, size);
}
}
@@ -0,0 +1,135 @@
package com.linkerbot.vibemake.service.impl;
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.Contracts.*;
import com.linkerbot.vibemake.bean.entity.*;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.service.InteractionService;
import com.linkerbot.vibemake.service.ProjectService;
import com.linkerbot.vibemake.service.UserService;
import com.linkerbot.vibemake.service.mapper.*;
import com.linkerbot.vibemake.service.state.RateLimits;
import com.linkerbot.vibemake.service.support.ProjectSupport;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class InteractionServiceImpl implements InteractionService {
private final RateLimits rateLimits;
private static final Logger log = LoggerFactory.getLogger(InteractionServiceImpl.class);
private final ProjectService projects;
private final UserService users;
private final CommentMapper comments;
private final LikeMapper likes;
@Override
public PageResponse<CommentView> list(String code, long page, long size) {
ProjectSupport.pageCheck(page, size);
Project project = projects.published(code);
Page<ProjectComment> result =
comments.selectPage(
new Page<>(page, size),
new LambdaQueryWrapper<ProjectComment>()
.eq(ProjectComment::getProjectId, project.getId())
.eq(ProjectComment::getDeleted, false)
.orderByDesc(ProjectComment::getCreatedAt)
.orderByDesc(ProjectComment::getId));
java.util.Map<Long, PublicUser> authors =
users.publicViews(
result.getRecords().stream()
.map(ProjectComment::getUserId)
.collect(java.util.stream.Collectors.toSet()));
return new PageResponse<>(
result.getRecords().stream()
.map(
comment ->
new CommentView(
comment.getCommentCode(),
authors.getOrDefault(
comment.getUserId(),
new PublicUser(null, "已删除用户")),
comment.getContent(),
comment.getCreatedAt()))
.toList(),
page,
size,
result.getTotal());
}
private CommentView view(ProjectComment comment) {
return new CommentView(
comment.getCommentCode(),
users.publicView(comment.getUserId()),
comment.getContent(),
comment.getCreatedAt());
}
@Override
public CommentView comment(long userId, String code, CommentInput input) {
rateLimits.operation("comment", userId);
users.require(userId);
Project project = projects.published(code);
ProjectComment comment = new ProjectComment();
comment.setCommentCode(Codes.next());
comment.setProjectId(project.getId());
comment.setUserId(userId);
comment.setContent(input.content().trim());
comment.setDeleted(false);
comment.setCreatedAt(ProjectSupport.now());
comment.setUpdatedAt(comment.getCreatedAt());
comments.insert(comment);
log.info("新增评论 projectCode={} commentCode={}", code, comment.getCommentCode());
return view(comment);
}
@Override
public void deleteComment(long userId, String code) {
int count =
comments.update(
null,
new LambdaUpdateWrapper<ProjectComment>()
.eq(ProjectComment::getCommentCode, code)
.eq(ProjectComment::getUserId, userId)
.eq(ProjectComment::getDeleted, false)
.set(ProjectComment::getDeleted, true)
.set(ProjectComment::getUpdatedAt, ProjectSupport.now()));
if (count == 0) throw BusinessException.notFound();
log.info("删除评论 commentCode={}", code);
}
@Override
public void like(long userId, String code) {
rateLimits.operation("like", userId);
users.require(userId);
Project project = projects.published(code);
ProjectLike like = new ProjectLike();
like.setProjectId(project.getId());
like.setUserId(userId);
like.setCreatedAt(ProjectSupport.now());
try {
likes.insert(like);
} catch (DuplicateKeyException duplicate) {
return;
}
log.info("点赞 projectCode={}", code);
}
@Override
public void unlike(long userId, String code) {
rateLimits.operation("like", userId);
Project project = projects.published(code);
likes.delete(
new LambdaQueryWrapper<ProjectLike>()
.eq(ProjectLike::getProjectId, project.getId())
.eq(ProjectLike::getUserId, userId));
log.info("取消点赞 projectCode={}", code);
}
}
@@ -0,0 +1,633 @@
package com.linkerbot.vibemake.service.impl;
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.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linkerbot.vibemake.bean.Contracts.*;
import com.linkerbot.vibemake.bean.entity.*;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.service.ProjectService;
import com.linkerbot.vibemake.service.UserService;
import com.linkerbot.vibemake.service.config.VibemakeProperties;
import com.linkerbot.vibemake.service.fork.ForkDeadline;
import com.linkerbot.vibemake.service.fork.ForkExecutor;
import com.linkerbot.vibemake.service.fork.GitSnapshotCopier;
import com.linkerbot.vibemake.service.gitea.*;
import com.linkerbot.vibemake.service.mapper.*;
import com.linkerbot.vibemake.service.oss.OssResourcePaths;
import com.linkerbot.vibemake.service.oss.UrdfResources;
import com.linkerbot.vibemake.service.state.RateLimits;
import com.linkerbot.vibemake.service.support.ProjectActors;
import com.linkerbot.vibemake.service.support.ProjectInputs;
import com.linkerbot.vibemake.service.support.ProjectLocks;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.function.Function;
@Service
@RequiredArgsConstructor
public class ProjectServiceImpl implements ProjectService {
private final ObjectProvider<RateLimits> rateLimits;
private static final Logger log = LoggerFactory.getLogger(ProjectServiceImpl.class);
private final ProjectMapper projects;
private final ProjectImportTaskMapper importTasks;
private final LikeMapper likes;
private final CommentMapper comments;
private final UserService users;
private final GiteaClient gitea;
private final VibemakeProperties config;
private final ProjectLocks locks;
private final OssResourcePaths resourcePaths;
// 离线导入只需地址转换配置,没有 URDF 时无需初始化 OSS 客户端。
private final ObjectProvider<UrdfResources> urdf;
private final ObjectProvider<ForkExecutor> forks;
private final ObjectProvider<GitSnapshotCopier> snapshots;
@Override
public List<TypeView> types() {
return config.getTypes().entrySet().stream()
.map(e -> new TypeView(e.getKey(), e.getValue()))
.toList();
}
private void validateInput(ProjectInput input) {
ProjectInputs.validate(input, config);
}
private String normalizeCoverUrl(String value) {
return resourcePaths.coverStorage(value);
}
@Override
public Project owner(long userId, String code) {
Project project =
projects.selectOne(
new LambdaQueryWrapper<Project>()
.eq(Project::getProjectCode, code)
.eq(!ProjectActors.isAdmin(), Project::getOwnerUserId, userId)
.eq(Project::getDeleted, false));
if (project == null) throw BusinessException.notFound();
return project;
}
@Override
public Project readyOwner(long userId, String code) {
Project project = owner(userId, code);
ready(project);
return project;
}
@Override
public void ready(Project project) {
if (!"READY".equals(project.getRepoStatus()))
throw BusinessException.conflict("仓库尚未就绪,请核对项目创建状态");
}
@Override
public Project published(String code) {
Project project =
projects.selectOne(
new LambdaQueryWrapper<Project>()
.eq(Project::getProjectCode, code)
.eq(Project::getDeleted, false)
.eq(Project::getRepoStatus, "READY")
.eq(Project::getPublishStatus, "PUBLISHED"));
if (project == null) throw BusinessException.notFound();
return project;
}
@Override
public GiteaClient.Repository repository(Project project) {
return new GiteaClient.Repository(
project.getGiteaRepoId(), project.getGiteaOwner(), project.getGiteaRepoName());
}
@Override
public ProjectView view(Project project, Long currentUser) {
return views(List.of(project), currentUser).getFirst();
}
@Override
public List<ProjectView> views(List<Project> records, Long currentUser) {
if (records.isEmpty()) return List.of();
Set<Long> ids = new HashSet<>();
Set<Long> ownerIds = new HashSet<>();
Set<Long> sourceIds = new HashSet<>();
List<String> codes = new ArrayList<>();
for (Project project : records) {
ids.add(project.getId());
ownerIds.add(project.getOwnerUserId());
codes.add(project.getProjectCode());
if (project.getSourceProjectId() != null) sourceIds.add(project.getSourceProjectId());
}
Map<Long, PublicUser> owners = users.publicViews(ownerIds);
Map<Long, Project> sources = new HashMap<>();
if (!sourceIds.isEmpty())
for (Project source :
projects.selectList(
new LambdaQueryWrapper<Project>()
.select(Project::getId, Project::getProjectCode)
.in(Project::getId, sourceIds)))
sources.put(source.getId(), source);
Map<Long, Long> likeCounts = new HashMap<>();
for (com.linkerbot.vibemake.service.support.EntityCount count : likes.counts(ids))
likeCounts.put(count.entityId(), count.total());
Map<Long, Long> commentCounts = new HashMap<>();
for (com.linkerbot.vibemake.service.support.EntityCount count : comments.counts(ids))
commentCounts.put(count.entityId(), count.total());
Set<Long> likedIds = new HashSet<>();
if (currentUser != null)
for (ProjectLike like :
likes.selectList(
new LambdaQueryWrapper<ProjectLike>()
.select(ProjectLike::getProjectId)
.in(ProjectLike::getProjectId, ids)
.eq(ProjectLike::getUserId, currentUser)))
likedIds.add(like.getProjectId());
Map<String, ProjectImportTask> imported = new HashMap<>();
for (ProjectImportTask task :
importTasks.selectList(
new LambdaQueryWrapper<ProjectImportTask>()
.select(
ProjectImportTask::getProjectCode,
ProjectImportTask::getSourceRepositoryUrl,
ProjectImportTask::getSourceLicense)
.in(ProjectImportTask::getProjectCode, codes)))
imported.put(task.getProjectCode(), task);
List<ProjectView> result = new ArrayList<>();
for (Project project : records)
result.add(
assemble(
project,
sources.get(project.getSourceProjectId()),
owners.getOrDefault(
project.getOwnerUserId(), new PublicUser(null, "已删除用户")),
likeCounts.getOrDefault(project.getId(), 0L),
commentCounts.getOrDefault(project.getId(), 0L),
likedIds.contains(project.getId()),
imported.get(project.getProjectCode())));
return List.copyOf(result);
}
private ProjectView assemble(
Project project,
Project source,
PublicUser owner,
long likeCount,
long commentCount,
boolean liked,
ProjectImportTask imported) {
String coverUrl;
String urdfMainUrl;
String urdfBaseUrl;
try {
coverUrl = resourcePaths.coverUrl(project.getCoverUrl());
urdfMainUrl = urdfUrl(project.getUrdfMainObjectKey());
urdfBaseUrl = urdfUrl(project.getUrdfPrefix());
} catch (BusinessException error) {
log.warn("项目资源地址生成失败 projectCode={} code={}", project.getProjectCode(), error.code());
throw error;
}
return new ProjectView(
project.getProjectCode(),
project.getName(),
project.getDescription(),
coverUrl,
urdfMainUrl,
urdfBaseUrl,
project.getProjectType(),
owner,
project.getRepoStatus(),
project.getPublishStatus(),
project.getPublishedCommitSha(),
project.getPublishedAt(),
source == null ? null : source.getProjectCode(),
project.getSourceCommitSha(),
likeCount,
commentCount,
liked,
imported == null ? null : imported.getSourceRepositoryUrl(),
imported == null ? null : imported.getSourceLicense(),
project.getCreatedAt(),
project.getUpdatedAt());
}
private String urdfUrl(String objectKey) {
return objectKey == null || objectKey.isEmpty() ? null : urdf.getObject().url(objectKey);
}
@Override
public PageResponse<ProjectView> list(
Long ownerId, String type, String keyword, long page, long size, Long currentUser) {
pageCheck(page, size);
// 社区优先展示已绑定 URDF 的项目,在数据库分页前排序。
LambdaQueryWrapper<Project> query =
new QueryWrapper<Project>()
.orderByDesc(
ownerId == null,
"CASE WHEN urdf_main_object_key <> '' THEN 1 ELSE 0 END")
.lambda()
.eq(Project::getDeleted, false);
// 列表不需要资源包清单,避免为每个项目读取可能很大的 JSON 字段。
query.select(Project.class, field -> !"urdfFiles".equals(field.getProperty()));
if (ownerId == null)
query.eq(Project::getRepoStatus, "READY")
.eq(Project::getPublishStatus, "PUBLISHED")
.orderByDesc(Project::getPublishedAt);
else query.eq(Project::getOwnerUserId, ownerId).orderByDesc(Project::getCreatedAt);
if (type != null && !type.isBlank()) query.eq(Project::getProjectType, type);
if (keyword != null && !keyword.isBlank()) {
if (keyword.length() > 200) throw BusinessException.badRequest("关键词过长");
query.and(
q ->
q.like(Project::getName, keyword)
.or()
.like(Project::getDescription, keyword));
}
query.orderByDesc(Project::getId);
Page<Project> result = projects.selectPage(new Page<>(page, size), query);
return new PageResponse<>(
views(result.getRecords(), currentUser), page, size, result.getTotal());
}
private Project initialize(long userId, ProjectInput input, Project source) {
return initialize(userId, input, source, null);
}
private Project initialize(
long userId, ProjectInput input, Project source, ForkDeadline deadline) {
if (source == null) validateInput(input);
else ProjectInputs.validateMetadata(input, config);
Project project = new Project();
project.setProjectCode(ProjectCodes.next());
project.setOwnerUserId(userId);
project.setName(input.name().trim());
project.setDescription(input.description() == null ? "" : input.description());
project.setCoverUrl(
source == null
? normalizeCoverUrl(input.coverUrl())
: resourcePaths.coverReference(source.getCoverUrl()));
project.setProjectType(input.projectType());
project.setGiteaOwner(config.getGitea().getOwner());
project.setGiteaRepoName("p_" + project.getProjectCode());
project.setRepoStatus("CREATING");
project.setPublishStatus("UNPUBLISHED");
project.setDeleted(false);
project.setCreatedAt(now());
project.setUpdatedAt(project.getCreatedAt());
if (source != null) {
project.setSourceProjectId(source.getId());
project.setSourceCommitSha(source.getPublishedCommitSha());
}
for (int attempt = 1; attempt <= 5; attempt++) {
try {
if (deadline != null) {
deadline.check();
deadline.projectCode(project.getProjectCode());
}
projects.insert(project);
return project;
} catch (DuplicateKeyException duplicate) {
boolean codeConflict = false;
for (Throwable cause = duplicate; cause != null; cause = cause.getCause()) {
if (cause.getMessage() != null
&& cause.getMessage()
.toLowerCase(Locale.ROOT)
.contains("uk_project_code")) codeConflict = true;
}
if (!codeConflict) throw duplicate;
log.warn("项目编码冲突 projectCode={} attempt={}", project.getProjectCode(), attempt);
if (attempt == 5)
throw new BusinessException(503, "PROJECT_CODE_EXHAUSTED", "项目编码分配失败,请稍后重试");
project.setId(null);
project.setProjectCode(ProjectCodes.next());
project.setGiteaRepoName("p_" + project.getProjectCode());
}
}
throw new IllegalStateException("项目编码分配未完成");
}
@Override
public ProjectView create(long userId, ProjectInput input) {
if (rateLimits.getIfAvailable() != null) rateLimits.getObject().operation("create", userId);
users.require(userId);
Project project = initialize(userId, input, null);
return locks.write(project.getProjectCode(), () -> createRemote(project));
}
@Override
public ProjectView fork(long userId, String sourceCode, ForkInput input) {
if (rateLimits.getIfAvailable() != null) rateLimits.getObject().operation("fork", userId);
User user = users.require(userId);
Project source = published(sourceCode);
if (!source.getPublishedCommitSha().equals(FilePaths.sha(input.publishedCommitSha())))
throw BusinessException.conflict("社区版本已更新,请刷新后 Fork");
ProjectInput data =
new ProjectInput(
input.name(),
source.getDescription(),
source.getProjectType(),
source.getCoverUrl());
ProjectInputs.validateMetadata(data, config);
ForkExecutor executor = forks.getIfAvailable();
if (executor == null) throw new BusinessException(503, "FORK_UNAVAILABLE", "当前进程未开启 Fork");
return executor.execute(
deadline -> {
deadline.check();
Project project;
try {
project = initialize(userId, data, source, deadline);
} catch (BusinessException error) {
throw error;
} catch (RuntimeException error) {
if (deadline.projectCode() != null)
locks.markUncertain(deadline.projectCode());
log.error(
"Fork 项目记录写入异常 projectCode={} sourceProjectCode={} errorType={}",
deadline.projectCode(),
sourceCode,
error.getClass().getSimpleName());
throw new BusinessException(
500,
"PROJECT_INITIALIZATION_ERROR",
"Fork 项目记录待核对,请按项目编码人工检查",
deadline.details());
}
return locks.write(
project.getProjectCode(),
() -> forkRemote(project, source, user, deadline));
});
}
private ProjectView forkRemote(
Project project, Project source, User user, ForkDeadline deadline) {
long started = System.nanoTime();
log.info(
"Fork 开始 projectCode={} sourceProjectCode={} sourceCommitSha={}",
project.getProjectCode(),
source.getProjectCode(),
project.getSourceCommitSha());
try (GitSnapshotCopier.PreparedSnapshot snapshot =
snapshots
.getObject()
.prepare(
repository(source),
project.getSourceCommitSha(),
user.getNickname(),
user.getUserCode(),
deadline)) {
deadline.beginWrite();
GiteaClient.Repository repo;
try {
repo = gitea.createRepository(project.getGiteaRepoName(), false);
} catch (GiteaFailure error) {
if (!error.uncertain()) deadline.confirmWrite();
throw error;
}
project.setGiteaRepoId(repo.id());
// 先保存仓库关联,再执行 Git/LFS 推送,便于中断后按项目编码核对。
if (projects.updateById(project) != 1) throw new IllegalStateException("Fork 仓库关联回写失败");
deadline.confirmWrite();
deadline.check();
String commit = snapshot.push(repo);
deadline.check();
if (source.getUrdfMainObjectKey() != null && !source.getUrdfMainObjectKey().isEmpty())
urdf.getObject().copy(source, project);
deadline.check();
project.setRepoStatus("READY");
project.setUpdatedAt(now());
if (projects.updateById(project) != 1) throw new IllegalStateException("Fork 完成状态回写失败");
log.info(
"Fork 完成 projectCode={} sourceProjectCode={} sourceCommitSha={}"
+ " snapshotCommitSha={} durationMs={}",
project.getProjectCode(),
source.getProjectCode(),
project.getSourceCommitSha(),
commit,
java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(
System.nanoTime() - started));
return view(project, project.getOwnerUserId());
} catch (RuntimeException error) {
boolean uncertain =
deadline.writing()
|| !(error instanceof BusinessException)
|| error instanceof GiteaFailure remote && remote.uncertain();
String code =
error instanceof BusinessException business
? business.code()
: "PROJECT_INITIALIZATION_ERROR";
int status = error instanceof BusinessException business ? business.status() : 500;
String message =
error instanceof BusinessException business
? business.getMessage()
: "Fork 初始化未完成,请按项目编码核对";
if (deadline.writing() && error instanceof BusinessException) {
code = "REMOTE_RESULT_UNKNOWN";
status = 504;
message = "Fork 远端写入结果待核对,请先查看工作区项目状态";
}
boolean interrupted = Thread.interrupted();
try {
project.setRepoStatus(uncertain ? "CREATING" : "FAILED");
project.setUpdatedAt(now());
if (uncertain) locks.markUncertain(project.getProjectCode());
if (projects.updateById(project) != 1)
throw new IllegalStateException("Fork 失败状态回写失败");
} catch (RuntimeException persistence) {
locks.markUncertain(project.getProjectCode());
log.error(
"Fork 状态回写异常 projectCode={} errorType={}",
project.getProjectCode(),
persistence.getClass().getSimpleName());
code = "PROJECT_INITIALIZATION_ERROR";
status = 500;
message = "Fork 状态未确认,请按项目编码人工核对";
} finally {
if (interrupted) Thread.currentThread().interrupt();
}
log.warn(
"Fork 失败 projectCode={} sourceProjectCode={} sourceCommitSha={} code={}"
+ " uncertain={} errorType={} durationMs={}",
project.getProjectCode(),
source.getProjectCode(),
project.getSourceCommitSha(),
code,
uncertain,
error.getClass().getSimpleName(),
java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(
System.nanoTime() - started));
throw new BusinessException(
status, code, message, Map.of("projectCode", project.getProjectCode()));
}
}
private ProjectView createRemote(Project project) {
try {
GiteaClient.Repository repo = gitea.createRepository(project.getGiteaRepoName(), true);
project.setGiteaRepoId(repo.id());
project.setRepoStatus("READY");
project.setUpdatedAt(now());
projects.updateById(project);
log.info("仓库创建完成 projectCode={} fork={}", project.getProjectCode(), false);
return view(project, project.getOwnerUserId());
} catch (GiteaFailure error) {
project.setRepoStatus(error.uncertain() ? "CREATING" : "FAILED");
project.setUpdatedAt(now());
projects.updateById(project);
if (error.uncertain()) locks.markUncertain(project.getProjectCode());
log.warn(
"仓库创建异常 projectCode={} code={} uncertain={}",
project.getProjectCode(),
error.code(),
error.uncertain());
throw new BusinessException(
error.status(),
error.code(),
error.getMessage(),
Map.of("projectCode", project.getProjectCode()));
} catch (BusinessException error) {
project.setRepoStatus("FAILED");
project.setUpdatedAt(now());
projects.updateById(project);
log.warn("项目初始化拒绝 projectCode={} code={}", project.getProjectCode(), error.code());
throw new BusinessException(
error.status(),
error.code(),
error.getMessage(),
Map.of("projectCode", project.getProjectCode()));
} catch (RuntimeException error) {
SafeExceptionLog.write(log, "仓库创建或回写异常 projectCode=" + project.getProjectCode(), error);
log.error(
"仓库创建或回写异常 projectCode={} type={}",
project.getProjectCode(),
error.getClass().getSimpleName());
throw new BusinessException(
500,
"PROJECT_INITIALIZATION_ERROR",
"项目初始化未完成,请按项目编码人工核对",
Map.of("projectCode", project.getProjectCode()));
}
}
@Override
public <T> T write(long userId, String code, Function<Project, T> action) {
return locks.write(
code,
() -> {
Project project = owner(userId, code);
try {
return action.apply(project);
} catch (GiteaFailure error) {
if (error.uncertain()) locks.markUncertain(code);
log.warn(
"仓库访问异常 projectCode={} code={} uncertain={}",
code,
error.code(),
error.uncertain());
throw new BusinessException(
error.status(),
error.code(),
error.getMessage(),
Map.of("projectCode", code));
}
});
}
@Override
public ProjectView update(long userId, String code, ProjectInput input) {
validateInput(input);
String coverUrl = normalizeCoverUrl(input.coverUrl());
return metadata(
userId,
code,
project -> {
project.setName(input.name().trim());
project.setDescription(input.description() == null ? "" : input.description());
project.setProjectType(input.projectType());
if (input.coverUrl() != null) project.setCoverUrl(coverUrl);
project.setUpdatedAt(now());
// 显式 SET,确保空字符串清除封面时实际写入 NULL;省略字段仍保留旧值。
projects.update(
null,
new LambdaUpdateWrapper<Project>()
.eq(Project::getProjectCode, code)
.set(Project::getName, project.getName())
.set(Project::getDescription, project.getDescription())
.set(Project::getProjectType, project.getProjectType())
.set(input.coverUrl() != null, Project::getCoverUrl, coverUrl)
.set(Project::getUpdatedAt, project.getUpdatedAt()));
if (input.coverUrl() != null)
log.info("更新项目封面 projectCode={} hasCover={}", code, coverUrl != null);
return view(project, userId);
});
}
@Override
public void delete(long userId, String code) {
metadata(
userId,
code,
project -> {
project.setDeleted(true);
project.setPublishStatus("UNPUBLISHED");
project.setUpdatedAt(now());
projects.updateById(project);
log.info("删除项目 projectCode={}", code);
return null;
});
}
@Override
public ProjectView publish(long userId, String code, String expectedSha) {
return write(
userId,
code,
project -> {
ready(project);
if ("BLOCKED".equals(project.getPublishStatus()))
throw new BusinessException(409, "PROJECT_BLOCKED", "项目已被管理员下架");
String head = gitea.head(repository(project));
if (!head.equals(FilePaths.sha(expectedSha)))
throw BusinessException.conflict("工作区版本已变化,请刷新后发布");
project.setPublishedCommitSha(head);
project.setPublishStatus("PUBLISHED");
project.setPublishedAt(now());
project.setUpdatedAt(now());
projects.updateById(project);
log.info("发布社区 projectCode={} commitSha={}", code, head);
return view(project, userId);
});
}
@Override
public void withdraw(long userId, String code) {
metadata(
userId,
code,
project -> {
// 撤回不能解除管理员下架,避免所有者先撤回再重新发布。
if (!"BLOCKED".equals(project.getPublishStatus()))
project.setPublishStatus("UNPUBLISHED");
project.setUpdatedAt(now());
projects.updateById(project);
log.info("撤回社区 projectCode={}", code);
return null;
});
}
private <T> T metadata(long userId, String code, Function<Project, T> action) {
return locks.serial(code, () -> action.apply(owner(userId, code)));
}
}
@@ -0,0 +1,96 @@
package com.linkerbot.vibemake.service.impl;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.linkerbot.vibemake.bean.Contracts.ProjectView;
import com.linkerbot.vibemake.bean.Contracts.UrdfConfirmInput;
import com.linkerbot.vibemake.bean.Contracts.UrdfUploadInput;
import com.linkerbot.vibemake.bean.Contracts.UrdfUploadSignature;
import com.linkerbot.vibemake.bean.entity.Project;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.ProjectService;
import com.linkerbot.vibemake.service.UrdfService;
import com.linkerbot.vibemake.service.mapper.ProjectMapper;
import com.linkerbot.vibemake.service.oss.UrdfResources;
import com.linkerbot.vibemake.service.state.RateLimits;
import com.linkerbot.vibemake.service.support.ProjectLocks;
import com.linkerbot.vibemake.service.support.ProjectSupport;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class UrdfServiceImpl implements UrdfService {
private final RateLimits rateLimits;
private static final Logger log = LoggerFactory.getLogger(UrdfServiceImpl.class);
private final ProjectService projects;
private final ProjectMapper mapper;
private final UrdfResources resources;
private final ProjectLocks locks;
@Override
public UrdfUploadSignature signature(long userId, String projectCode, UrdfUploadInput input) {
rateLimits.operation("urdf-sign", userId);
projects.readyOwner(userId, projectCode);
return resources.sign(projectCode, input.files());
}
@Override
public ProjectView confirm(long userId, String projectCode, UrdfConfirmInput input) {
projects.readyOwner(userId, projectCode);
// OSS 网络调用在锁外执行,最终落库时重新检查项目归属及状态。
resources.verify(projectCode, input.batchCode(), input.files());
String prefix = resources.prefix(projectCode, input.batchCode());
String main = resources.validate(prefix, input.files());
String manifest = resources.manifest(input.files());
return locks.serial(
projectCode,
() -> {
Project project = projects.readyOwner(userId, projectCode);
project.setUrdfPrefix(prefix);
project.setUrdfMainObjectKey(prefix + main);
project.setUrdfFiles(manifest);
persist(project);
log.info(
"绑定 URDF 资源 projectCode={} batchCode={} fileCount={}",
projectCode,
input.batchCode(),
input.files().size());
return projects.view(project, userId);
});
}
@Override
public void clear(long userId, String projectCode) {
locks.serial(
projectCode,
() -> {
Project project = projects.owner(userId, projectCode);
project.setUrdfMainObjectKey("");
project.setUrdfPrefix("");
project.setUrdfFiles("[]");
persist(project);
log.info("清除 URDF 绑定 projectCode={}", projectCode);
return null;
});
}
private void persist(Project project) {
project.setUpdatedAt(ProjectSupport.now());
int updated =
mapper.update(
null,
new LambdaUpdateWrapper<Project>()
.eq(Project::getProjectCode, project.getProjectCode())
.eq(Project::getOwnerUserId, project.getOwnerUserId())
.eq(Project::getDeleted, false)
.set(Project::getUrdfMainObjectKey, project.getUrdfMainObjectKey())
.set(Project::getUrdfFiles, project.getUrdfFiles())
.set(Project::getUrdfPrefix, project.getUrdfPrefix())
.set(Project::getUpdatedAt, project.getUpdatedAt()));
if (updated != 1) throw BusinessException.notFound();
}
}
@@ -0,0 +1,106 @@
package com.linkerbot.vibemake.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linkerbot.vibemake.bean.Contracts.*;
import com.linkerbot.vibemake.bean.entity.User;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.service.UserService;
import com.linkerbot.vibemake.service.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.Locale;
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
private static final int MAX_CODE_ATTEMPTS = 5;
private final UserMapper users;
@Override
public User login(String email) {
String normalized = email.trim().toLowerCase(Locale.ROOT);
if (com.linkerbot.vibemake.service.support.OfficialUsers.EMAIL.equals(normalized))
throw new BusinessException(403, "ACCOUNT_DISABLED", "账号不可用");
User user = users.selectOne(new LambdaQueryWrapper<User>().eq(User::getEmail, normalized));
if (user == null) user = create(normalized);
if (!"ACTIVE".equals(user.getStatus()) || !"USER".equals(user.getRole()))
throw new BusinessException(403, "ACCOUNT_DISABLED", "账号不可用");
log.info("用户登录 userCode={}", user.getUserCode());
return user;
}
private User create(String normalizedEmail) {
for (int attempt = 1; attempt <= MAX_CODE_ATTEMPTS; attempt++) {
User candidate = new User();
candidate.setUserCode(UserCodes.next());
candidate.setEmail(normalizedEmail);
candidate.setNickname("用户_" + candidate.getUserCode().substring(0, 8));
candidate.setStatus("ACTIVE");
candidate.setCreatedAt(LocalDateTime.now(Clock.systemUTC()));
candidate.setUpdatedAt(candidate.getCreatedAt());
try {
users.insert(candidate);
log.info("创建用户 userCode={}", candidate.getUserCode());
return candidate;
} catch (DuplicateKeyException duplicate) {
// 同一邮箱并发首次登录时,复用另一个请求已创建的用户。
User existing =
users.selectOne(
new LambdaQueryWrapper<User>().eq(User::getEmail, normalizedEmail));
if (existing != null) return existing;
User conflict =
users.selectOne(
new LambdaQueryWrapper<User>()
.eq(User::getUserCode, candidate.getUserCode()));
if (conflict == null) throw duplicate;
log.warn("用户编码冲突 userCode={} attempt={}", candidate.getUserCode(), attempt);
if (attempt == MAX_CODE_ATTEMPTS)
throw new BusinessException(503, "USER_CODE_EXHAUSTED", "用户编码分配失败,请稍后重试");
}
}
throw new IllegalStateException("用户编码分配未完成");
}
@Override
public User require(long id) {
User user = users.selectById(id);
if (user == null || !"ACTIVE".equals(user.getStatus()))
throw new BusinessException(401, "UNAUTHORIZED", "请重新登录");
return user;
}
@Override
public UserView view(User user) {
return new UserView(user.getUserCode(), user.getNickname(), user.getEmail());
}
@Override
public PublicUser publicView(long id) {
User user = users.selectById(id);
return user == null
? new PublicUser(null, "已删除用户")
: new PublicUser(user.getUserCode(), user.getNickname());
}
@Override
public java.util.Map<Long, PublicUser> publicViews(java.util.Collection<Long> ids) {
if (ids.isEmpty()) return java.util.Map.of();
java.util.Map<Long, PublicUser> result = new java.util.HashMap<>();
for (User user :
users.selectList(
new LambdaQueryWrapper<User>()
.select(User::getId, User::getUserCode, User::getNickname)
.in(User::getId, ids)))
result.put(user.getId(), new PublicUser(user.getUserCode(), user.getNickname()));
return result;
}
}
@@ -0,0 +1,44 @@
package com.linkerbot.vibemake.service.mapper;
import com.linkerbot.vibemake.bean.entity.Project;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface AiProjectMapper {
@Select(
"""
<script>
SELECT id, project_code, name, description, project_type, published_commit_sha FROM project
WHERE deleted = 0 AND repo_status = 'READY' AND publish_status = 'PUBLISHED'
<if test="projectType != null">AND project_type = #{projectType}</if>
<if test="!focusCodes.isEmpty()">
AND project_code IN
<foreach collection="focusCodes" item="code" open="(" close=")" separator=",">#{code}</foreach>
</if>
<if test="!patterns.isEmpty()">
AND (<foreach collection="patterns" item="word" separator=" OR ">
(LOWER(name) LIKE #{word} ESCAPE '!' OR LOWER(description) LIKE #{word} ESCAPE '!')
</foreach>)
</if>
ORDER BY
<if test="!patterns.isEmpty()">
(<foreach collection="patterns" item="word" separator=" + ">
CASE WHEN LOWER(name) LIKE #{word} ESCAPE '!' THEN 1 ELSE 0 END
</foreach>) DESC,
(<foreach collection="patterns" item="word" separator=" + ">
CASE WHEN LOWER(description) LIKE #{word} ESCAPE '!' THEN 1 ELSE 0 END
</foreach>) DESC,
</if>
published_at DESC, id DESC LIMIT 20
</script>
""")
List<Project> candidates(
@Param("projectType") String projectType,
@Param("patterns") List<String> patterns,
@Param("focusCodes") List<String> focusCodes);
}
@@ -0,0 +1,19 @@
package com.linkerbot.vibemake.service.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.vibemake.bean.entity.ProjectComment;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface CommentMapper extends BaseMapper<ProjectComment> {
@org.apache.ibatis.annotations.Select(
"""
<script>SELECT project_id AS entity_id, COUNT(*) AS total FROM project_comment
WHERE deleted = 0 AND project_id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
GROUP BY project_id</script>
""")
java.util.List<com.linkerbot.vibemake.service.support.EntityCount> counts(
@org.apache.ibatis.annotations.Param("ids") java.util.Collection<Long> ids);
}
@@ -0,0 +1,19 @@
package com.linkerbot.vibemake.service.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.vibemake.bean.entity.ProjectLike;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface LikeMapper extends BaseMapper<ProjectLike> {
@org.apache.ibatis.annotations.Select(
"""
<script>SELECT project_id AS entity_id, COUNT(*) AS total FROM project_like
WHERE project_id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
GROUP BY project_id</script>
""")
java.util.List<com.linkerbot.vibemake.service.support.EntityCount> counts(
@org.apache.ibatis.annotations.Param("ids") java.util.Collection<Long> ids);
}
@@ -0,0 +1,6 @@
package com.linkerbot.vibemake.service.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.vibemake.bean.entity.ProjectImportTask;
public interface ProjectImportTaskMapper extends BaseMapper<ProjectImportTask> {}
@@ -0,0 +1,19 @@
package com.linkerbot.vibemake.service.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.vibemake.bean.entity.Project;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ProjectMapper extends BaseMapper<Project> {
@org.apache.ibatis.annotations.Select(
"""
<script>SELECT owner_user_id AS entity_id, COUNT(*) AS total FROM project
WHERE deleted = 0 AND owner_user_id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
GROUP BY owner_user_id</script>
""")
java.util.List<com.linkerbot.vibemake.service.support.EntityCount> ownerCounts(
@org.apache.ibatis.annotations.Param("ids") java.util.Collection<Long> ids);
}
@@ -0,0 +1,9 @@
package com.linkerbot.vibemake.service.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.vibemake.bean.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {}
@@ -0,0 +1,245 @@
package com.linkerbot.vibemake.service.migration;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.InputStream;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GitHubSourceChecks {
public record Repository(
long id,
String url,
String defaultBranch,
String name,
String description,
String license) {
public Repository(long id, String url, String branch) {
this(id, url, branch, repositoryKey(url).split("/")[1], "", null);
}
}
private final HttpClient http =
HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NEVER)
.build();
private final ObjectMapper json = new ObjectMapper();
private final String token;
private volatile long apiLimitedUntil;
public GitHubSourceChecks(String token) {
this.token = token == null ? "" : token;
}
public Repository repository(String url) throws Exception {
if (System.nanoTime() < apiLimitedUntil) return publicPage(url);
URI uri =
URI.create("https://api.github.com/repos/" + GitHubSourceChecks.repositoryKey(url));
for (int redirects = 0; redirects <= 5; redirects++) {
if (!"https".equalsIgnoreCase(uri.getScheme())
|| !"api.github.com".equalsIgnoreCase(uri.getHost())
|| uri.getUserInfo() != null
|| (uri.getPort() != -1 && uri.getPort() != 443))
throw new MigrationFailure("GITHUB_REDIRECT", "GitHub API 跳转地址不符合要求");
HttpRequest.Builder request =
HttpRequest.newBuilder(uri)
.timeout(Duration.ofSeconds(30))
.header("Accept", "application/vnd.github+json")
.header("User-Agent", "vibemake-import/1");
if (!token.isBlank()) request.header("Authorization", "Bearer " + token);
HttpResponse<String> response =
http.send(request.GET().build(), HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
if (status >= 300 && status < 400) {
uri = redirect(uri, response);
continue;
}
if (status == 403 || status == 429) {
apiLimitedUntil = System.nanoTime() + Duration.ofMinutes(5).toNanos();
return publicPage(url);
}
if (status == 404) throw new MigrationFailure("GITHUB_NOT_FOUND", "GitHub 仓库不可访问");
if (status != 200) throw new MigrationFailure("GITHUB_HTTP_" + status, "GitHub 返回异常状态");
JsonNode data = json.readTree(response.body());
if (!data.path("private").isBoolean()
|| data.path("id").asLong() <= 0
|| data.path("private").asBoolean()
|| data.path("default_branch").asText().isBlank()
|| data.path("size").asLong(-1) < 0)
throw new MigrationFailure("GITHUB_INVALID_REPOSITORY", "仓库元数据无效或不是公开仓库");
String canonical =
"https://github.com/"
+ GitHubSourceChecks.repositoryKey(data.path("html_url").asText());
return new Repository(
data.path("id").asLong(),
canonical,
data.path("default_branch").asText(),
data.path("name").asText(),
data.path("description").asText(""),
data.path("license").path("spdx_id").asText(null));
}
throw new MigrationFailure("GITHUB_REDIRECT", "GitHub 跳转次数过多");
}
private Repository publicPage(String url) throws Exception {
URI uri = URI.create("https://github.com/" + GitHubSourceChecks.repositoryKey(url));
for (int redirects = 0; redirects <= 5; redirects++) {
if (!"https".equalsIgnoreCase(uri.getScheme())
|| !"github.com".equalsIgnoreCase(uri.getHost())
|| uri.getUserInfo() != null
|| (uri.getPort() != -1 && uri.getPort() != 443))
throw new MigrationFailure("GITHUB_REDIRECT", "GitHub 网页跳转地址不符合要求");
HttpRequest request =
HttpRequest.newBuilder(uri)
.timeout(Duration.ofSeconds(30))
.header("Accept", "text/html")
.header("User-Agent", "vibemake-import/1")
.GET()
.build();
// 网页请求不携带任何 GitHub 或 Gitea 凭据。
HttpResponse<String> response =
http.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
if (status >= 300 && status < 400) {
uri = redirect(uri, response);
continue;
}
if (status == 403 || status == 429)
throw new MigrationFailure("GITHUB_ACCESS_OR_RATE_LIMIT", "GitHub API 及公开网页均不可访问");
if (status != 200)
throw new MigrationFailure("GITHUB_PAGE_HTTP_" + status, "GitHub 公开仓库网页不可访问");
return parsePublicPage(response.body(), uri.toString());
}
throw new MigrationFailure("GITHUB_REDIRECT", "GitHub 网页跳转次数过多");
}
public static Repository parsePublicPage(String html, String url) throws Exception {
String key = GitHubSourceChecks.repositoryKey(url);
String id = pageMeta(html, "repository_id");
if (!id.matches("[1-9][0-9]*")
|| !key.equalsIgnoreCase(pageMeta(html, "repository_nwo"))
|| !"true".equals(pageMeta(html, "repository_public")))
throw new MigrationFailure("GITHUB_PAGE_METADATA", "GitHub 网页仓库身份或公开状态无法核验");
Matcher scripts =
Pattern.compile(
"<script[^>]*data-target=\"react-app.embeddedData\"[^>]*>(.*?)</script>",
Pattern.DOTALL)
.matcher(html);
while (scripts.find()) {
JsonNode repo =
new ObjectMapper()
.readTree(scripts.group(1))
.path("payload")
.path("codeViewLayoutRoute")
.path("repo");
if (repo.path("id").asLong() != Long.parseLong(id)) continue;
String name = repo.path("ownerLogin").asText() + "/" + repo.path("name").asText();
if (!name.equalsIgnoreCase(key)
|| !repo.path("public").asBoolean()
|| !repo.path("private").isBoolean()
|| repo.path("private").asBoolean()
|| !repo.path("isEmpty").isBoolean()
|| repo.path("isEmpty").asBoolean()
|| repo.path("defaultBranch").asText().isBlank()) break;
return new Repository(
Long.parseLong(id),
"https://github.com/" + name,
repo.path("defaultBranch").asText());
}
throw new MigrationFailure("GITHUB_PAGE_METADATA", "GitHub 网页缺少一致的仓库 ID、公开状态或默认分支");
}
private static String pageMeta(String html, String field) {
Matcher meta =
Pattern.compile(
"<meta name=\"octolytics-dimension-"
+ field
+ "\" content=\"([^\"]*)\"[^>]*>")
.matcher(html);
return meta.find() ? meta.group(1) : "";
}
public void cover(String url) throws Exception {
URI uri = URI.create(url);
for (int redirects = 0; redirects <= 5; redirects++) {
if (!"https".equalsIgnoreCase(uri.getScheme())
|| uri.getHost() == null
|| uri.getUserInfo() != null)
throw new MigrationFailure("COVER_REDIRECT", "封面跳转地址必须为 HTTPS");
HttpRequest request =
HttpRequest.newBuilder(uri)
.timeout(Duration.ofSeconds(30))
.header("User-Agent", "vibemake-import/1")
.header("Range", "bytes=0-511")
.GET()
.build();
HttpResponse<InputStream> response =
http.send(request, HttpResponse.BodyHandlers.ofInputStream());
try (InputStream body = response.body()) {
int status = response.statusCode();
if (status >= 300 && status < 400) {
uri = redirect(uri, response);
continue;
}
if (status != 200 && status != 206)
throw new MigrationFailure("COVER_HTTP_" + status, "封面链接无法读取");
byte[] signature = body.readNBytes(16);
boolean image =
signature.length >= 3
&& ((signature[0] & 255) == 255 && (signature[1] & 255) == 216
|| signature.length >= 8
&& (signature[0] & 255) == 137
&& signature[1] == 'P'
&& signature[2] == 'N'
&& signature[3] == 'G'
|| signature[0] == 'G'
&& signature[1] == 'I'
&& signature[2] == 'F'
|| signature.length >= 12
&& signature[0] == 'R'
&& signature[1] == 'I'
&& signature[8] == 'W'
&& signature[9] == 'E');
if (!image)
throw new MigrationFailure("COVER_NOT_IMAGE", "封面未返回 JPG、PNG、GIF 或 WebP 图片内容");
return;
}
}
throw new MigrationFailure("COVER_REDIRECT", "封面跳转次数过多");
}
private URI redirect(URI uri, HttpResponse<?> response) {
return uri.resolve(
response.headers()
.firstValue("Location")
.orElseThrow(
() -> new MigrationFailure("INVALID_REDIRECT", "跳转响应缺少 Location")));
}
public static String repositoryKey(String url) {
if (url == null) throw new IllegalArgumentException("仓库地址为空");
URI uri = URI.create(url.trim());
String path = uri.getRawPath() == null ? "" : uri.getRawPath().replaceAll("/$", "");
if (!"https".equalsIgnoreCase(uri.getScheme())
|| !"github.com".equalsIgnoreCase(uri.getHost())
|| uri.getUserInfo() != null
|| (uri.getPort() != -1 && uri.getPort() != 443)
|| uri.getQuery() != null
|| uri.getFragment() != null
|| !path.matches("/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+"))
throw new IllegalArgumentException("必须是 GitHub 仓库根地址");
if (path.endsWith(".git")) path = path.substring(0, path.length() - 4);
String[] parts = path.substring(1).split("/");
if (parts.length != 2
|| parts[0].equals(".")
|| parts[0].equals("..")
|| parts[1].equals(".")
|| parts[1].equals("..")) throw new IllegalArgumentException("仓库地址不合法");
return path.substring(1).toLowerCase(java.util.Locale.ROOT);
}
}
@@ -0,0 +1,13 @@
package com.linkerbot.vibemake.service.migration;
import com.linkerbot.vibemake.service.config.AdminProperties;
import org.springframework.context.annotation.*;
@Configuration
public class MigrationConfiguration {
@Bean
public GitHubSourceChecks gitHubSourceChecks(AdminProperties properties) {
return new GitHubSourceChecks(properties.getGithubToken());
}
}
@@ -0,0 +1,9 @@
package com.linkerbot.vibemake.service.migration;
import com.linkerbot.vibemake.common.BusinessException;
public class MigrationFailure extends BusinessException {
public MigrationFailure(String code, String message) {
super(409, code, message);
}
}
@@ -0,0 +1,131 @@
package com.linkerbot.vibemake.service.migration;
import com.linkerbot.vibemake.service.gitea.*;
import java.io.IOException;
import java.time.Duration;
/** 不依赖 Web、Excel 或状态存储;迁移收据在任何后续远端写入前持久化。 */
public final class RepositoryMigration {
public interface Progress {
GiteaClient.RemoteRepository receipt();
String targetSha();
default String migrationDescription() { return null; }
void receipt(GiteaClient.RemoteRepository receipt) throws IOException;
void targetSha(String sha) throws IOException;
void phase(String phase) throws IOException;
}
public record Result(GiteaClient.RemoteRepository remote, String sha) {}
private final GiteaClient gitea;
private final String organization;
public RepositoryMigration(GiteaClient gitea, String organization) {
this.gitea = gitea;
this.organization = organization;
}
public Result run(
String sourceUrl,
String originalUrl,
String branch,
String name,
Duration timeout,
Progress progress)
throws IOException {
if (progress.receipt() == null) {
ensureAbsent(name);
progress.phase("MIGRATING");
String description = progress.migrationDescription();
GiteaClient.RemoteRepository receipt = description == null
? gitea.migrate(sourceUrl + ".git", name, timeout)
: gitea.migrate(sourceUrl + ".git", name, timeout, description);
progress.receipt(receipt);
}
GiteaClient.RemoteRepository remote = gitea.inspect(name);
validate(remote, sourceUrl, originalUrl, name, progress.receipt());
progress.phase("NORMALIZING");
String sha = gitea.branch(remote.repository(), branch);
if (progress.targetSha() != null && !progress.targetSha().equals(sha))
throw new MigrationFailure("SOURCE_BRANCH_CHANGED", "目标仓库的源分支已变化,禁止改写冻结版本");
if (progress.targetSha() == null) progress.targetSha(sha);
String main;
try {
main = gitea.branch(remote.repository(), "main");
} catch (GiteaFailure missing) {
if (missing.status() != 404) throw missing;
gitea.createBranch(remote.repository(), "main", sha);
main = gitea.branch(remote.repository(), "main");
}
if (!sha.equals(main))
throw new MigrationFailure("MAIN_BRANCH_CONFLICT", "main与原默认分支内容不同,禁止覆盖");
if (!"main".equals(remote.defaultBranch()))
gitea.defaultBranch(remote.repository(), "main");
progress.phase("BRANCH_READY");
return new Result(remote, sha);
}
/** 结果不明时只读核对,绝不重发分支写入。 */
public Result verifyNormalized(
String sourceUrl,
String branch,
String name,
GiteaClient.RemoteRepository receipt,
String sha) {
GiteaClient.RemoteRepository remote = gitea.inspect(name);
validate(remote, sourceUrl, sourceUrl, name, receipt);
if (sha == null
|| !"main".equals(remote.defaultBranch())
|| !sha.equals(gitea.branch(remote.repository(), branch))
|| !sha.equals(gitea.branch(remote.repository(), "main")))
throw new MigrationFailure("NORMALIZATION_NOT_CONFIRMED", "分支适配结果尚未确认,禁止重新写入");
return new Result(remote, sha);
}
public GiteaClient.RemoteRepository verifyReceipt(
String source, String name, GiteaClient.RemoteRepository receipt) {
GiteaClient.RemoteRepository remote = gitea.inspect(name);
validate(remote, source, source, name, receipt);
return remote;
}
public void ensureAbsent(String name) {
try {
gitea.inspect(name);
} catch (GiteaFailure missing) {
if (missing.status() == 404) return;
throw missing;
}
throw new MigrationFailure("REMOTE_ALREADY_EXISTS", "目标仓库已存在但没有成功收据,需人工核对");
}
private void validate(
GiteaClient.RemoteRepository remote,
String source,
String original,
String name,
GiteaClient.RemoteRepository receipt) {
String key;
try {
key = GitHubSourceChecks.repositoryKey(remote.originalUrl());
} catch (RuntimeException error) {
throw new MigrationFailure("SOURCE_CONFLICT", "目标仓库缺少合法来源");
}
if (!organization.equals(remote.owner())
|| !name.equals(remote.name())
|| !remote.privateRepo()
|| remote.mirror()
|| remote.empty()
|| !(key.equals(GitHubSourceChecks.repositoryKey(source))
|| key.equals(GitHubSourceChecks.repositoryKey(original))))
throw new MigrationFailure("REPOSITORY_CONFLICT", "目标仓库归属、来源或可见性不符合要求");
if (receipt == null || remote.id() != receipt.id())
throw new MigrationFailure("REPOSITORY_REPLACED", "目标仓库与迁移收据不一致");
}
}
@@ -0,0 +1,135 @@
package com.linkerbot.vibemake.service.oss;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.config.OssProperties;
import com.linkerbot.vibemake.service.fork.ForkDeadline;
import com.linkerbot.vibemake.service.gitea.GiteaFailure;
import jakarta.annotation.PreDestroy;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class AliyunOssObjectStore implements OssObjectStore {
private static final Logger log = LoggerFactory.getLogger(AliyunOssObjectStore.class);
private final OssProperties properties;
private OSS client;
private final ThreadLocal<OSSClient> forkClients = new ThreadLocal<>();
private synchronized OSS client() {
if (!properties.isEnabled())
throw new BusinessException(503, "OSS_UNAVAILABLE", "OSS URDF 上传暂未开启");
ForkDeadline deadline = ForkDeadline.current();
if (deadline != null) {
deadline.check();
OSSClient bounded = forkClients.get();
if (bounded == null) {
ClientBuilderConfiguration configuration = configuration();
configuration.setRequestTimeoutEnabled(true);
configuration.setMaxErrorRetry(0);
bounded = (OSSClient) build(configuration);
forkClients.set(bounded);
OSSClient owned = bounded;
deadline.onClose(() -> { forkClients.remove(); owned.shutdown(); });
}
int remaining = (int) Math.min(30000, Math.max(1, deadline.remaining().toMillis()));
bounded.getClientConfiguration().setRequestTimeout(remaining);
bounded.getClientConfiguration().setSocketTimeout(remaining);
bounded.getClientConfiguration().setConnectionTimeout(Math.min(5000, remaining));
bounded.getClientConfiguration().setConnectionRequestTimeout(Math.min(5000, remaining));
return bounded;
}
if (client == null) {
client = build(configuration());
}
return client;
}
private ClientBuilderConfiguration configuration() {
ClientBuilderConfiguration configuration = new ClientBuilderConfiguration();
configuration.setSignatureVersion(SignVersion.V4);
configuration.setConnectionTimeout(5000);
configuration.setSocketTimeout(30000);
configuration.setMaxErrorRetry(1);
return configuration;
}
private OSS build(ClientBuilderConfiguration configuration) {
return OSSClientBuilder.create()
.endpoint(properties.resolvedEndpoint())
.region(properties.getRegion())
.credentialsProvider(new DefaultCredentialProvider(
properties.getAccessKeyId(), properties.getAccessKeySecret()))
.clientConfiguration(configuration)
.build();
}
@Override
public Metadata head(String objectKey) {
try {
ObjectMetadata metadata = client().getObjectMetadata(properties.getBucket(), objectKey);
return new Metadata(metadata.getContentLength(), metadata.getETag());
} catch (OSSException error) {
throw failure("head", objectKey, error);
} catch (ClientException error) {
ForkDeadline.checkpoint();
throw transportFailure("head", objectKey, error);
}
}
@Override
public void copy(String sourceKey, String targetKey, String sourceEtag) {
ForkDeadline deadline = ForkDeadline.current();
if (deadline != null) deadline.beginWrite();
try {
CopyObjectRequest request = new CopyObjectRequest(
properties.getBucket(), sourceKey, properties.getBucket(), targetKey);
request.setMatchingETagConstraints(List.of(sourceEtag));
client().copyObject(request);
if (deadline != null) deadline.confirmWrite();
} catch (OSSException error) {
if (deadline != null) deadline.confirmWrite();
throw failure("copy", targetKey, error);
} catch (ClientException error) {
if (deadline != null) {
deadline.check();
throw new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "Fork OSS 复制结果待核对", true);
}
throw transportFailure("copy", targetKey, error);
}
}
private BusinessException failure(String operation, String key, OSSException error) {
log.warn("URDF OSS 请求失败 operation={} objectKey={} ossCode={} requestId={}",
operation, key, error.getErrorCode(), error.getRequestId());
if ("NoSuchKey".equals(error.getErrorCode()))
return new BusinessException(400, "URDF_FILE_MISSING", "URDF 文件未上传完整,请重新上传");
if ("PreconditionFailed".equals(error.getErrorCode()))
return BusinessException.conflict("URDF 资源已变化,请重新操作");
return new BusinessException(502, "OSS_ERROR", "OSS 资源访问失败,请稍后重试");
}
private BusinessException transportFailure(String operation, String key, ClientException error) {
log.warn("URDF OSS 连接失败 operation={} objectKey={} errorType={}",
operation, key, error.getClass().getSimpleName());
return new BusinessException(502, "OSS_ERROR", "OSS 资源访问失败,请稍后重试");
}
@PreDestroy
public synchronized void close() {
if (client != null) client.shutdown();
}
}
@@ -0,0 +1,10 @@
package com.linkerbot.vibemake.service.oss;
/** URDF 所需的 OSS 操作边界,测试使用内存实现。 */
public interface OssObjectStore {
record Metadata(long sizeBytes, String etag) {}
Metadata head(String objectKey);
void copy(String sourceKey, String targetKey, String sourceEtag);
}
@@ -0,0 +1,127 @@
package com.linkerbot.vibemake.service.oss;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.bean.Contracts.CoverUploadSignature;
import com.linkerbot.vibemake.common.Codes;
import com.linkerbot.vibemake.service.config.OssProperties;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
public class OssPostSigner {
private static final Logger log = LoggerFactory.getLogger(OssPostSigner.class);
public static final long MAX_FILE_BYTES = 5L * 1024 * 1024;
private static final Duration VALIDITY = Duration.ofMinutes(5);
private static final String VERSION = "OSS4-HMAC-SHA256";
private static final DateTimeFormatter DATE =
DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC);
private static final DateTimeFormatter TIMESTAMP =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
private static final DateTimeFormatter EXPIRATION =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
private final OssProperties properties;
private final ObjectMapper json;
private final Clock clock;
private final OssResourcePaths resourcePaths;
@Autowired
public OssPostSigner(OssProperties properties, ObjectMapper json) {
this(properties, json, Clock.systemUTC());
}
OssPostSigner(OssProperties properties, ObjectMapper json, Clock clock) {
this.properties = properties;
this.json = json;
this.clock = clock;
this.resourcePaths = new OssResourcePaths(properties);
}
public CoverUploadSignature sign(String userCode, String contentType, String extension) {
String key = properties.getRootDirectory() + "/project-covers/" + userCode + "/"
+ DATE.format(clock.instant()) + "/" + Codes.next() + "." + extension;
SignedPost post = post(key, contentType, 1, MAX_FILE_BYTES, VALIDITY, false);
return new CoverUploadSignature(properties.uploadUrl(), key,
resourcePaths.publicUrl(key), post.expiresAt(), post.formFields());
}
public record SignedPost(LocalDateTime expiresAt, Map<String, String> formFields) {}
public SignedPost signObject(String key, String contentType, long sizeBytes) {
return post(key, contentType, sizeBytes, sizeBytes, Duration.ofMinutes(15), true);
}
private SignedPost post(String key, String contentType, long minBytes, long maxBytes,
Duration validity, boolean forbidOverwrite) {
Instant now = clock.instant().truncatedTo(ChronoUnit.MILLIS);
Instant expiration = now.plus(validity);
String date = DATE.format(now);
String timestamp = TIMESTAMP.format(now);
String credential = properties.getAccessKeyId() + "/" + date + "/"
+ properties.getRegion() + "/oss/aliyun_v4_request";
Map<String, Object> policy = new LinkedHashMap<>();
policy.put("expiration", EXPIRATION.format(expiration));
List<Object> conditions = new ArrayList<>(List.of(
Map.of("bucket", properties.getBucket()),
Map.of("x-oss-signature-version", VERSION),
Map.of("x-oss-credential", credential),
Map.of("x-oss-date", timestamp),
List.of("eq", "$key", key),
List.of("eq", "$content-type", contentType),
List.of("content-length-range", minBytes, maxBytes),
List.of("eq", "$success_action_status", "200")));
if (forbidOverwrite) {
conditions.add(List.of("eq", "$x-oss-forbid-overwrite", "true"));
conditions.add(List.of("eq", "$x-oss-content-type", contentType));
}
policy.put("conditions", conditions);
try {
String encoded = Base64.getEncoder().encodeToString(json.writeValueAsBytes(policy));
Map<String, String> fields = new LinkedHashMap<>();
fields.put("key", key);
fields.put("policy", encoded);
fields.put("x-oss-signature-version", VERSION);
fields.put("x-oss-credential", credential);
fields.put("x-oss-date", timestamp);
fields.put("x-oss-signature", signature(properties.getAccessKeySecret(), date,
properties.getRegion(), encoded));
fields.put("content-type", contentType);
fields.put("success_action_status", "200");
if (forbidOverwrite) {
fields.put("x-oss-forbid-overwrite", "true");
fields.put("x-oss-content-type", contentType);
}
return new SignedPost(LocalDateTime.ofInstant(expiration, ZoneOffset.UTC), Map.copyOf(fields));
} catch (JsonProcessingException | GeneralSecurityException error) {
log.error("OSS 签名生成失败 objectKey={} region={} errorType={}",
key, properties.getRegion(), error.getClass().getSimpleName());
throw new IllegalStateException("OSS 签名生成失败");
}
}
// OSS POST V4:Base64 Policy 为待签名文本,所有输入均按 UTF-8 编码。
static String signature(String secret, String date, String region, String policy)
throws GeneralSecurityException {
byte[] key = hmac(("aliyun_v4" + secret).getBytes(StandardCharsets.UTF_8), date);
key = hmac(key, region);
key = hmac(key, "oss");
key = hmac(key, "aliyun_v4_request");
return HexFormat.of().formatHex(hmac(key, policy));
}
private static byte[] hmac(byte[] key, String value) throws GeneralSecurityException {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(value.getBytes(StandardCharsets.UTF_8));
}
}
@@ -0,0 +1,121 @@
package com.linkerbot.vibemake.service.oss;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.common.FilePaths;
import com.linkerbot.vibemake.service.config.OssProperties;
import com.linkerbot.vibemake.service.support.ProjectInputs;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;
/** 仅转换资源地址,不访问 OSS,也不依赖上传凭据。存储路径为未编码的环境相对路径。 */
@Component
@RequiredArgsConstructor
public class OssResourcePaths {
private final OssProperties oss;
/** 外部请求仍只接受 HTTPS URL;仅转换明确属于当前环境的托管封面。 */
public String coverStorage(String value) {
String url = ProjectInputs.coverUrl(value);
if (url == null) return null;
URI candidate = URI.create(url);
if (candidate.getRawQuery() != null || candidate.getRawFragment() != null) return url;
for (String baseValue : managedBases()) {
URI base = URI.create(baseValue);
if (!sameOrigin(candidate, base)) continue;
String prefix = base.getRawPath().replaceAll("/+$", "")
+ "/" + oss.getRootDirectory() + "/project-covers/";
if (!candidate.getRawPath().startsWith(prefix)) continue;
try {
String[] segments = candidate.getRawPath().substring(prefix.length()).split("/", -1);
for (int index = 0; index < segments.length; index++) {
segments[index] = UriUtils.decode(segments[index], StandardCharsets.UTF_8);
// 保留含歧义分隔符或 UTF-8 替换字符的原地址,避免引用到不同对象。
if (segments[index].contains("/") || segments[index].indexOf('\uFFFD') >= 0) return url;
}
return storagePath("/project-covers/" + String.join("/", segments));
} catch (IllegalArgumentException | BusinessException error) {
// 非规范地址保留原语义,不进行路径折叠或二次解码。
return url;
}
}
return url;
}
/** 内部 Fork 可以复用已持久化的路径,不走客户端 URL 校验。 */
public String coverReference(String value) {
if (value != null && value.startsWith("/project-covers/")) return storagePath(value);
return coverStorage(value);
}
public String coverUrl(String value) {
String reference = coverReference(value);
return reference != null && reference.startsWith("/project-covers/")
? publicUrl(reference) : reference;
}
/** 兼容当前环境的旧 key;绝不把其他环境的 key 重定位至当前环境。 */
public String storagePath(String value) {
if (value == null || value.isEmpty()) throw invalidPath();
String path = value;
String root = oss.getRootDirectory();
if (root != null && !root.isBlank() && path.startsWith(root + "/"))
path = path.substring(root.length());
if (!path.startsWith("/project-covers/") && !path.startsWith("/urdf/")) throw invalidPath();
String relative = path.substring(1);
if (relative.endsWith("/")) relative = relative.substring(0, relative.length() - 1);
try {
FilePaths.file(relative);
} catch (BusinessException error) {
throw invalidPath();
}
return path;
}
public String objectKey(String value) {
String path = storagePath(value);
String root = oss.getRootDirectory();
if (root == null || !root.matches("[A-Za-z0-9_-]+"))
throw new BusinessException(503, "OSS_UNAVAILABLE", "OSS 资源根目录未正确配置");
return root + path;
}
public String publicUrl(String value) {
if (value == null || value.isEmpty()) return null;
String[] segments = objectKey(value).split("/", -1);
for (int index = 0; index < segments.length; index++)
segments[index] = UriUtils.encodePathSegment(segments[index], StandardCharsets.UTF_8);
return oss.publicBaseUrl() + "/" + String.join("/", segments);
}
private List<String> managedBases() {
List<String> bases = new ArrayList<>(oss.getLegacyPublicBaseUrls());
if (oss.getPublicBaseUrl() != null && !oss.getPublicBaseUrl().isBlank())
bases.add(oss.getPublicBaseUrl());
if (oss.getBucket() != null && !oss.getBucket().isBlank()
&& oss.getRegion() != null && !oss.getRegion().isBlank()) {
bases.add("https://" + oss.getBucket() + ".oss-" + oss.getRegion() + ".aliyuncs.com");
bases.add(oss.uploadUrl());
}
return bases;
}
private boolean sameOrigin(URI first, URI second) {
return second.getHost() != null
&& first.getScheme().equalsIgnoreCase(second.getScheme())
&& first.getHost().equalsIgnoreCase(second.getHost())
&& port(first) == port(second);
}
private int port(URI uri) {
return uri.getPort() == -1 ? 443 : uri.getPort();
}
private BusinessException invalidPath() {
return new BusinessException(500, "RESOURCE_PATH_INVALID", "资源存储路径异常");
}
}
@@ -0,0 +1,190 @@
package com.linkerbot.vibemake.service.oss;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.bean.Contracts.UrdfFile;
import com.linkerbot.vibemake.bean.Contracts.UrdfFileSignature;
import com.linkerbot.vibemake.bean.Contracts.UrdfUploadSignature;
import com.linkerbot.vibemake.bean.entity.Project;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.common.Codes;
import com.linkerbot.vibemake.common.FilePaths;
import com.linkerbot.vibemake.service.config.OssProperties;
import com.linkerbot.vibemake.service.config.UrdfProperties;
import com.linkerbot.vibemake.service.fork.ForkDeadline;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaTypeFactory;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class UrdfResources {
private static final Logger log = LoggerFactory.getLogger(UrdfResources.class);
private static final TypeReference<List<UrdfFile>> FILES_TYPE = new TypeReference<>() {};
private final OssProperties oss;
private final UrdfProperties limits;
private final OssPostSigner signer;
private final OssObjectStore store;
private final ObjectMapper json;
private final OssResourcePaths paths;
public void requireEnabled() {
if (!oss.isEnabled())
throw new BusinessException(503, "OSS_UNAVAILABLE", "OSS URDF 上传暂未开启");
}
/** 不信任客户端文件名及大小;签名、确认和 Fork 使用同一套校验。 */
public String validate(String prefix, List<UrdfFile> files) {
if (files == null) throw BusinessException.badRequest("必须提供 URDF 文件清单");
if (files.size() > limits.getMaxFiles()) throw tooLarge();
Set<String> seenPaths = new HashSet<>();
long total = 0;
String main = null;
int mainCount = 0;
for (UrdfFile file : files) {
if (file == null || file.sizeBytes() == null || file.sizeBytes() < 0)
throw BusinessException.badRequest("文件大小不合法");
String path = FilePaths.file(file.relativePath());
if (!seenPaths.add(path)) throw BusinessException.badRequest("上传路径不能重复");
String key = paths.objectKey(prefix + path);
if (key.length() > 512 || key.getBytes(StandardCharsets.UTF_8).length > 1023)
throw BusinessException.badRequest("URDF 文件对象键过长");
if (file.sizeBytes() > limits.getMaxFileBytes()
|| file.sizeBytes() > limits.getMaxTotalBytes() - total) throw tooLarge();
total += file.sizeBytes();
if (path.toLowerCase(Locale.ROOT).endsWith(".urdf")) {
main = path;
mainCount++;
}
}
if (mainCount == 0)
throw new BusinessException(400, "URDF_MAIN_FILE_INVALID", "文件夹中未找到 URDF 文件");
if (mainCount > 1)
throw new BusinessException(400, "URDF_MAIN_FILE_INVALID",
"文件夹中存在多个 URDF 文件,请仅保留一个后重新上传");
return main;
}
private BusinessException tooLarge() {
return new BusinessException(413, "URDF_UPLOAD_TOO_LARGE", "URDF 文件数量或大小超过限制");
}
public String prefix(String projectCode, String batchCode) {
if (projectCode == null || !projectCode.matches("[a-z0-9]{12}|[a-z0-9]{32}")
|| batchCode == null || !batchCode.matches("[a-f0-9]{32}"))
throw BusinessException.badRequest("URDF 项目或批次编码不合法");
return "/urdf/" + projectCode + "/" + batchCode + "/";
}
public UrdfUploadSignature sign(String projectCode, List<UrdfFile> files) {
requireEnabled();
String batch = Codes.next();
String prefix = prefix(projectCode, batch);
String main = validate(prefix, files);
List<UrdfFileSignature> signatures = new ArrayList<>();
LocalDateTime expiration = null;
for (UrdfFile file : files) {
String type = file.relativePath().equals(main) ? "application/xml"
: MediaTypeFactory.getMediaType(file.relativePath().toLowerCase(Locale.ROOT))
.map(Object::toString).orElse("application/octet-stream");
String key = paths.objectKey(prefix + file.relativePath());
OssPostSigner.SignedPost post = signer.signObject(key, type, file.sizeBytes());
if (expiration == null || post.expiresAt().isBefore(expiration)) expiration = post.expiresAt();
signatures.add(new UrdfFileSignature(file.relativePath(), key, post.formFields()));
}
log.info("生成 URDF 上传签名 projectCode={} batchCode={} fileCount={} totalBytes={}",
projectCode, batch, files.size(), totalBytes(files));
return new UrdfUploadSignature(batch, main, oss.uploadUrl(), expiration, List.copyOf(signatures));
}
public void verify(String projectCode, String batchCode, List<UrdfFile> files) {
requireEnabled();
String prefix = prefix(projectCode, batchCode);
validate(prefix, files);
for (UrdfFile file : files) checkedMetadata(prefix, file);
}
private OssObjectStore.Metadata checkedMetadata(String prefix, UrdfFile file) {
ForkDeadline.checkpoint();
String key = paths.objectKey(prefix + file.relativePath());
OssObjectStore.Metadata metadata = store.head(key);
if (metadata.sizeBytes() != file.sizeBytes()) {
log.warn("URDF 文件大小不符 objectKey={} expectedBytes={} actualBytes={}",
key, file.sizeBytes(), metadata.sizeBytes());
throw new BusinessException(400, "URDF_FILE_SIZE_MISMATCH", "URDF 文件大小不符,请重新上传");
}
return metadata;
}
public String manifest(List<UrdfFile> files) {
try {
return json.writeValueAsString(files);
} catch (JsonProcessingException error) {
throw new IllegalStateException("URDF 文件清单序列化失败", error);
}
}
public void copy(Project source, Project target) {
if (source.getUrdfMainObjectKey() == null || source.getUrdfMainObjectKey().isEmpty()) return;
requireEnabled();
List<UrdfFile> files;
try {
files = json.readValue(source.getUrdfFiles(), FILES_TYPE);
} catch (JsonProcessingException error) {
log.error("URDF 文件清单读取失败 projectCode={} errorType={}",
source.getProjectCode(), error.getClass().getSimpleName());
throw new BusinessException(500, "URDF_MANIFEST_INVALID", "URDF 文件清单异常");
}
String sourcePrefix;
String sourceMain;
try {
sourcePrefix = paths.storagePath(source.getUrdfPrefix());
sourceMain = paths.storagePath(source.getUrdfMainObjectKey());
} catch (BusinessException error) {
log.warn("Fork URDF 路径异常 sourceProjectCode={} projectCode={} code={}",
source.getProjectCode(), target.getProjectCode(), error.code());
throw new BusinessException(500, "URDF_MANIFEST_INVALID", "URDF 资源路径异常");
}
String root = "/urdf/" + source.getProjectCode() + "/";
if (sourcePrefix == null || !sourcePrefix.startsWith(root)
|| !sourcePrefix.substring(root.length()).matches("[a-f0-9]{32}/"))
throw new BusinessException(500, "URDF_MANIFEST_INVALID", "URDF 资源目录异常");
String main = validate(sourcePrefix, files);
if (!sourceMain.equals(sourcePrefix + main))
throw new BusinessException(500, "URDF_MANIFEST_INVALID", "URDF 主文件记录异常");
String targetPrefix = prefix(target.getProjectCode(), Codes.next());
validate(targetPrefix, files);
log.info("开始复制 Fork URDF sourceProjectCode={} projectCode={} fileCount={}",
source.getProjectCode(), target.getProjectCode(), files.size());
for (UrdfFile file : files) {
OssObjectStore.Metadata metadata = checkedMetadata(sourcePrefix, file);
ForkDeadline.checkpoint();
store.copy(paths.objectKey(sourcePrefix + file.relativePath()),
paths.objectKey(targetPrefix + file.relativePath()), metadata.etag());
}
ForkDeadline.checkpoint();
target.setUrdfPrefix(targetPrefix);
target.setUrdfMainObjectKey(targetPrefix + main);
target.setUrdfFiles(manifest(files));
log.info("Fork URDF 复制完成 projectCode={} fileCount={} totalBytes={}",
target.getProjectCode(), files.size(), totalBytes(files));
}
public String url(String objectKey) {
return paths.publicUrl(objectKey);
}
private long totalBytes(List<UrdfFile> files) {
return files.stream().mapToLong(UrdfFile::sizeBytes).sum();
}
}
@@ -0,0 +1,88 @@
package com.linkerbot.vibemake.service.state;
import com.linkerbot.vibemake.service.config.LimitProperties;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class ClientAddresses {
private final List<Network> trusted;
public ClientAddresses(LimitProperties properties) {
trusted = properties.getTrustedProxies().stream().map(Network::parse).toList();
}
public String resolve(HttpServletRequest request) {
String peer = canonical(request.getRemoteAddr());
if (!trusted(peer)) return peer;
String forwarded = request.getHeader("X-Forwarded-For");
if (forwarded == null || forwarded.length() > 4096) return peer;
String current = peer;
String[] chain = forwarded.split(",", -1);
for (int index = chain.length - 1; index >= 0 && trusted(current); index--) {
String candidate = chain[index].trim();
// 只接收数字 IP,不做 DNS 查询;保留原始连接地址作为异常输入的安全默认值。
if (!candidate.matches("[0-9a-fA-F:.]{2,45}")) return peer;
try {
Network.address(candidate);
} catch (IllegalArgumentException error) {
return peer;
}
current = canonical(candidate);
}
return current;
}
private boolean trusted(String address) {
return address != null && trusted.stream().anyMatch(matcher -> matcher.matches(address));
}
private static String canonical(String address) {
try {
return java.net.InetAddress.getByAddress(Network.address(address)).getHostAddress();
} catch (IllegalArgumentException | java.net.UnknownHostException error) {
return "unknown";
}
}
private record Network(byte[] bytes, int bits) {
static Network parse(String cidr) {
String[] parts = cidr.split("/", -1);
byte[] bytes = address(parts[0]);
int bits = parts.length == 1 ? bytes.length * 8 : Integer.parseInt(parts[1]);
if (parts.length > 2 || bits < 0 || bits > bytes.length * 8)
throw new IllegalArgumentException("可信代理 CIDR 不合法");
return new Network(bytes, bits);
}
static byte[] address(String value) {
if (value == null
|| !(value.matches("[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+")
|| value.contains(":") && value.matches("[0-9a-fA-F:.]+")))
throw new IllegalArgumentException("IP 不合法");
try {
return java.net.InetAddress.getByName(value).getAddress();
} catch (java.net.UnknownHostException error) {
throw new IllegalArgumentException("IP 不合法");
}
}
boolean matches(String value) {
byte[] other;
try {
other = address(value);
} catch (IllegalArgumentException error) {
return false;
}
if (other.length != bytes.length) return false;
for (int bit = 0; bit < bits; bit++)
if ((other[bit / 8] & (1 << (7 - bit % 8)))
!= (bytes[bit / 8] & (1 << (7 - bit % 8)))) return false;
return true;
}
}
}
@@ -0,0 +1,170 @@
package com.linkerbot.vibemake.service.state;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.service.config.LimitProperties;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.concurrent.Semaphore;
/** 在安全链的 CORS 之后、请求正文解析之前执行;不预先复制请求体。 */
@Component
public class HttpSafetyFilter extends OncePerRequestFilter {
private final LimitProperties properties;
private final RateLimits limits;
private final ClientAddresses addresses;
private final ObjectMapper json;
private final Semaphore files;
public HttpSafetyFilter(
LimitProperties properties,
RateLimits limits,
ClientAddresses addresses,
ObjectMapper json) {
this.properties = properties;
this.limits = limits;
this.addresses = addresses;
this.json = json;
files = new Semaphore(properties.getFileConcurrent());
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
String path = request.getServletPath();
if (path.isEmpty()) path = request.getRequestURI();
return "OPTIONS".equals(request.getMethod())
|| !(path.startsWith("/api/") || path.startsWith("/admin-api/"));
}
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String path =
request.getServletPath().isEmpty()
? request.getRequestURI()
: request.getServletPath();
String method = request.getMethod();
boolean read = "GET".equals(method) || "HEAD".equals(method);
boolean acquired = false;
try {
if (path.contains("/auth/") || path.endsWith("/signature"))
response.setHeader("Cache-Control", "no-store");
String ip = addresses.resolve(request);
if (path.equals("/api/auth/captcha")) limits.request("captcha", ip);
else if (path.equals("/api/auth/login")) limits.request("login-ip", ip);
else if (path.equals("/admin-api/auth/login")) limits.request("admin-login", ip);
else if (read
&& path.matches(
"/(api/community|api/workspace|admin-api)/projects/[^/]+/files"))
limits.request("file-read", ip);
else if (read && path.startsWith("/api/community/"))
limits.request("vibemake-read", ip);
boolean fileOperation =
("GET".equals(method) || "HEAD".equals(method))
&& path.matches(
"/(api/workspace|api/community|admin-api)/projects/[^/]+/(files|tree|commits)")
|| "POST".equals(method)
&& path.matches(
"/(api/workspace|admin-api)/projects/[^/]+/(commits|uploads/commit)");
if (fileOperation) {
acquired = files.tryAcquire();
if (!acquired) throw new RateLimitedException("FILE_BUSY", "文件服务繁忙,请稍后重试", 1);
}
String contentType = request.getContentType();
if (contentType != null && contentType.toLowerCase(Locale.ROOT).contains("json")) {
long maximum =
path.endsWith("/commits") && "POST".equals(method)
? properties.getCommitJsonBytes()
: path.contains("/urdf")
? properties.getUrdfJsonBytes()
: properties.getJsonBytes();
if (request.getContentLengthLong() > maximum) throw new RequestTooLargeException();
chain.doFilter(new LimitedRequest(request, maximum), response);
} else chain.doFilter(request, response);
} catch (BusinessException error) {
if (!response.isCommitted()) HttpFailures.write(response, json, error);
else throw error;
} finally {
if (acquired) files.release();
}
}
private static final class LimitedRequest extends HttpServletRequestWrapper {
private final ServletInputStream stream;
LimitedRequest(HttpServletRequest request, long maximum) throws IOException {
super(request);
ServletInputStream input = request.getInputStream();
stream =
new ServletInputStream() {
private long count;
private void counted(int size) {
if (size > 0 && (count += size) > maximum)
throw new RequestTooLargeException();
}
@Override
public int read() throws IOException {
int value = input.read();
if (value >= 0) counted(1);
return value;
}
@Override
public int read(byte[] bytes, int offset, int length) throws IOException {
int size =
input.read(
bytes,
offset,
(int)
Math.min(
length,
Math.max(1, maximum - count + 1)));
counted(size);
return size;
}
@Override
public boolean isFinished() {
return input.isFinished();
}
@Override
public boolean isReady() {
return input.isReady();
}
@Override
public void setReadListener(ReadListener listener) {
input.setReadListener(listener);
}
};
}
@Override
public ServletInputStream getInputStream() {
return stream;
}
@Override
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
}
}
}
@@ -0,0 +1,56 @@
package com.linkerbot.vibemake.service.state;
import com.linkerbot.vibemake.common.RateLimitedException;
import com.linkerbot.vibemake.common.SecurityHashes;
import com.linkerbot.vibemake.common.state.TransientStateStore;
import com.linkerbot.vibemake.service.config.LimitProperties;
import com.linkerbot.vibemake.service.support.ProjectActors;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
@Component
@RequiredArgsConstructor
public class RateLimits {
private static final Logger log = LoggerFactory.getLogger(RateLimits.class);
private final TransientStateStore state;
private final LimitProperties properties;
private final ConcurrentHashMap<String, AtomicLong> lastLogs = new ConcurrentHashMap<>();
public void operation(String group, long userId) {
String actor =
ProjectActors.isAdmin()
? "admin:" + ProjectActors.admin().userCode()
: "user:" + userId;
request(group, actor);
}
public void request(String group, String subject) {
if (!properties.isEnabled()) return;
Integer limit = properties.getPerMinute().get(group);
if (limit == null) throw new IllegalArgumentException("未配置的限流规则");
check(group, subject, limit, Duration.ofMinutes(1), "RATE_LIMITED", "请求过于频繁,请稍后重试");
}
/** AI 和后台失败计数使用自身既有配置,不依赖普通业务限流开关。 */
public void check(
String group, String subject, int limit, Duration window, String code, String message) {
TransientStateStore.Window result =
state.increment(
"rate:" + group + ":" + SecurityHashes.sha256(subject), window, false);
if (result.count() <= limit) return;
AtomicLong last = lastLogs.computeIfAbsent(group, ignored -> new AtomicLong());
long previous = last.get();
long now = System.nanoTime();
if ((previous == 0 || now - previous > Duration.ofMinutes(1).toNanos())
&& last.compareAndSet(previous, now)) log.warn("请求限流 rule={} code={}", group, code);
throw new RateLimitedException(code, message, result.retryAfterSeconds());
}
}
@@ -0,0 +1,35 @@
package com.linkerbot.vibemake.service.state;
import com.linkerbot.vibemake.common.state.TransientStateStore;
import com.linkerbot.vibemake.service.config.RedisStateProperties;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
@Configuration(proxyBeanMethods = false)
public class RedisStateConfiguration {
@Bean
@ConditionalOnMissingBean(TransientStateStore.class)
public TransientStateStore transientStateStore(
StringRedisTemplate redis, RedisStateProperties properties) {
return new RedisStateStore(redis, properties);
}
@Bean
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public SmartInitializingSingleton verifyRedisSecurityState(
TransientStateStore state, ApplicationArguments arguments) {
// 在 ContextRefreshedEvent 之前验证,避免 Redis 尚未就绪时定时导入任务已开始写入。
return () -> {
if (arguments.containsOption("bootstrap-admin-user-code")) return;
state.verify();
LoggerFactory.getLogger(RedisStateConfiguration.class).info("Redis 安全状态校验通过");
};
}
}
@@ -0,0 +1,138 @@
package com.linkerbot.vibemake.service.state;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.common.Codes;
import com.linkerbot.vibemake.common.state.TransientStateStore;
import com.linkerbot.vibemake.service.config.RedisStateProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
public final class RedisStateStore implements TransientStateStore {
private static final Logger log = LoggerFactory.getLogger(RedisStateStore.class);
private static final DefaultRedisScript<List> INCREMENT =
new DefaultRedisScript<>(
"""
local n = redis.call('INCR', KEYS[1])
if n == 1 or ARGV[2] == '1' then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
local ttl = redis.call('PTTL', KEYS[1])
if ttl < 0 then redis.call('PEXPIRE', KEYS[1], ARGV[1]); ttl = tonumber(ARGV[1]) end
return {n, ttl}
""",
List.class);
private final StringRedisTemplate redis;
private final String prefix;
private final AtomicLong lastFailureLog = new AtomicLong();
private final AtomicLong suppressed = new AtomicLong();
public RedisStateStore(StringRedisTemplate redis, RedisStateProperties properties) {
this.redis = redis;
this.prefix = properties.prefix();
}
private <T> T execute(String operation, Supplier<T> action) {
try {
return action.get();
} catch (RuntimeException error) {
long now = System.nanoTime();
long previous = lastFailureLog.get();
suppressed.incrementAndGet();
if ((previous == 0 || now - previous > Duration.ofMinutes(1).toNanos())
&& lastFailureLog.compareAndSet(previous, now)) {
log.error(
"Redis 安全状态访问失败 operation={} errorType={} failureCount={}",
operation,
error.getClass().getSimpleName(),
suppressed.getAndSet(0));
com.linkerbot.vibemake.common.SafeExceptionLog.write(
log, "Redis operation=" + operation, error);
}
throw new BusinessException(503, "REDIS_UNAVAILABLE", "安全状态服务暂不可用,请稍后重试");
}
}
@Override
public boolean putIfAbsent(String key, String value, Duration ttl) {
return execute(
"set",
() ->
Boolean.TRUE.equals(
redis.opsForValue().setIfAbsent(prefix + key, value, ttl)));
}
@Override
public String get(String key) {
return execute("get", () -> redis.opsForValue().get(prefix + key));
}
@Override
public String consume(String key) {
return execute("getdel", () -> redis.opsForValue().getAndDelete(prefix + key));
}
@Override
public void remove(String key) {
execute("del", () -> redis.delete(prefix + key));
}
@Override
public long remainingSeconds(String key) {
return execute(
"ttl",
() -> {
Long ttl = redis.getExpire(prefix + key, java.util.concurrent.TimeUnit.SECONDS);
return ttl == null ? 0L : Math.max(0, ttl);
});
}
@Override
public Window increment(String key, Duration ttl, boolean refreshTtl) {
return execute(
"increment",
() -> {
List<?> result =
redis.execute(
INCREMENT,
List.of(prefix + key),
Long.toString(ttl.toMillis()),
refreshTtl ? "1" : "0");
if (result == null || result.size() != 2)
throw new IllegalStateException("Redis 计数响应异常");
return new Window(
((Number) result.get(0)).longValue(),
Math.max(1, (((Number) result.get(1)).longValue() + 999) / 1000));
});
}
@Override
public void verify() {
String probe = "probe:" + Codes.next();
String counter = probe + ":counter";
try {
checked("set", putIfAbsent(probe, "ready", Duration.ofSeconds(10)));
checked("get", "ready".equals(get(probe)));
checked("getdel", "ready".equals(consume(probe)));
checked("increment", increment(counter, Duration.ofSeconds(10), false).count() == 1);
checked("ttl", remainingSeconds(counter) > 0);
checked("refresh", increment(counter, Duration.ofSeconds(10), true).count() == 2);
} finally {
remove(probe);
remove(counter);
}
}
private void checked(String operation, boolean successful) {
if (!successful) {
log.error("Redis 安全状态校验失败 operation={}", operation);
throw new BusinessException(
503, "REDIS_UNAVAILABLE", "Redis 安全状态校验失败 operation=" + operation);
}
}
}
@@ -0,0 +1,3 @@
package com.linkerbot.vibemake.service.support;
public record EntityCount(long entityId, long total) {}
@@ -0,0 +1,7 @@
package com.linkerbot.vibemake.service.support;
public final class OfficialUsers {
public static final String EMAIL = "vibemake-official@internal.invalid";
private OfficialUsers() {}
}
@@ -0,0 +1,43 @@
package com.linkerbot.vibemake.service.support;
import com.linkerbot.vibemake.bean.entity.User;
import com.linkerbot.vibemake.service.UserService;
/** 仅由已鉴权的管理端入口设置;不从请求参数推断管理员身份。 */
public final class ProjectActors {
private static final ThreadLocal<AdminActor> ADMIN = new ThreadLocal<>();
private ProjectActors() {}
public record AdminActor(String userCode, String nickname) {}
public record Author(String code, String nickname) {}
public static AdminActor admin() {
return ADMIN.get();
}
public static boolean isAdmin() {
return admin() != null;
}
public static Scope enter(AdminActor actor) {
AdminActor previous = ADMIN.get();
ADMIN.set(actor);
return () -> {
if (previous == null) ADMIN.remove();
else ADMIN.set(previous);
};
}
public interface Scope extends AutoCloseable {
@Override
void close();
}
public static Author author(UserService users, long userId) {
if (isAdmin()) return new Author(admin().userCode(), admin().nickname());
User user = users.require(userId);
return new Author(user.getUserCode(), user.getNickname());
}
}
@@ -0,0 +1,42 @@
package com.linkerbot.vibemake.service.support;
import com.linkerbot.vibemake.bean.Contracts.ProjectInput;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.config.VibemakeProperties;
import java.net.URI;
public final class ProjectInputs {
private ProjectInputs() {}
public static void validate(ProjectInput input, VibemakeProperties config) {
validateMetadata(input, config);
coverUrl(input.coverUrl());
}
public static void validateMetadata(ProjectInput input, VibemakeProperties config) {
if (input.name() == null || input.name().isBlank() || input.name().length() > 100)
throw BusinessException.badRequest("项目名称必须为 1~100 字符");
if (input.description() != null && input.description().length() > 2000)
throw BusinessException.badRequest("项目描述不能超过 2000 字符");
if (!config.getTypes().containsKey(input.projectType()))
throw BusinessException.badRequest("项目类型不在可选列表中");
}
public static String coverUrl(String value) {
if (value == null || value.isBlank()) return null;
String normalized = value.trim();
try {
URI uri = URI.create(normalized);
if (normalized.length() > 2048
|| !"https".equalsIgnoreCase(uri.getScheme())
|| uri.getHost() == null
|| uri.getRawUserInfo() != null
|| (uri.getPort() != -1 && (uri.getPort() < 1 || uri.getPort() > 65535)))
throw new IllegalArgumentException();
} catch (IllegalArgumentException error) {
throw BusinessException.badRequest("封面地址必须是最多 2048 字符且不含用户凭据的 HTTPS 地址");
}
return normalized;
}
}
@@ -0,0 +1,215 @@
package com.linkerbot.vibemake.service.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.linkerbot.vibemake.bean.entity.Project;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.gitea.GiteaFailure;
import com.linkerbot.vibemake.service.mapper.ProjectMapper;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
import javax.sql.DataSource;
/** 数据库命名锁不持有业务事务;专用连接在整个项目操作期间保持占用。 */
@Component
public class ProjectLocks {
private static final org.slf4j.Logger log =
org.slf4j.LoggerFactory.getLogger(ProjectLocks.class);
private final ReentrantLock[] locks = new ReentrantLock[128];
private final Set<String> uncertain = ConcurrentHashMap.newKeySet();
private final ThreadLocal<Set<String>> held = ThreadLocal.withInitial(HashSet::new);
private final ThreadLocal<Map<String, Connection>> connections =
ThreadLocal.withInitial(HashMap::new);
private final ThreadLocal<Set<String>> writing = ThreadLocal.withInitial(HashSet::new);
private final ProjectMapper projects;
private final HikariDataSource lockPool;
private final String namespace;
/** 供不启动 Spring 的单元测试使用。生产构造器不会降级为本地锁。 */
public ProjectLocks() {
this.projects = null;
this.lockPool = null;
this.namespace = "unit";
initialize();
}
@Autowired
public ProjectLocks(DataSource source, ProjectMapper projects) {
this.projects = projects;
if (!(source instanceof HikariDataSource hikari))
throw new IllegalStateException("项目锁需要 Hikari 数据源");
String database = hikari.getJdbcUrl().split("\\?", 2)[0];
this.namespace =
Integer.toHexString(database.substring(database.lastIndexOf('/') + 1).hashCode());
if (hikari.getJdbcUrl().startsWith("jdbc:h2:")) {
this.lockPool = null; // H2 工作流测试;MySQL 互斥由真实数据库集成测试覆盖。
} else {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(hikari.getJdbcUrl());
config.setUsername(hikari.getUsername());
config.setPassword(hikari.getPassword());
config.setMaximumPoolSize(8);
config.setMinimumIdle(0);
config.setConnectionTimeout(5000);
config.setPoolName("ProjectLockPool");
this.lockPool = new HikariDataSource(config);
}
initialize();
}
private void initialize() {
for (int i = 0; i < locks.length; i++) locks[i] = new ReentrantLock();
}
public <T> T write(String code, Supplier<T> action) {
return serial(
code,
() -> {
if (writing.get().contains(code)) return action.get();
Project guard = guard(code);
if (uncertain.contains(code)
|| guard != null && !"IDLE".equals(guard.getRepoWriteStatus())) {
markUncertain(code);
throw blocked();
}
state(code, "WRITING");
writing.get().add(code);
try {
T result = action.get();
Connection connection = connections.get().get(code);
if (connection != null) {
try {
if (!connection.isValid(1)) throw new SQLException("持锁连接已断开");
} catch (SQLException error) {
throw new BusinessException(
503, "PROJECT_LOCK_UNAVAILABLE", "持锁连接已断开,请核对操作结果");
}
}
if (!uncertain.contains(code)) state(code, "IDLE");
return result;
} catch (RuntimeException error) {
boolean unknown =
!(error instanceof BusinessException)
|| error instanceof GiteaFailure remote
&& remote.uncertain()
|| error instanceof BusinessException business
&& business.status() >= 500
&& !(error instanceof GiteaFailure remote
&& !remote.uncertain());
if (unknown || uncertain.contains(code)) markUncertain(code);
else state(code, "IDLE");
throw error;
} finally {
writing.get().remove(code);
if (writing.get().isEmpty()) writing.remove();
}
});
}
public <T> T serial(String code, Supplier<T> action) {
if (held.get().contains(code)) return action.get();
ReentrantLock lock = locks[Math.floorMod(code.hashCode(), locks.length)];
try {
if (!lock.tryLock(3, TimeUnit.SECONDS))
throw new BusinessException(409, "PROJECT_BUSY", "项目正在处理,请稍后重试");
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw new BusinessException(503, "PROJECT_LOCK_INTERRUPTED", "等待项目锁被中断");
}
boolean executed = false;
String name = "vibemake:" + namespace + ":" + code;
try (Connection connection = lockPool == null ? null : lockPool.getConnection()) {
if (connection != null && !lockFunction(connection, "GET_LOCK", name, true))
throw new BusinessException(409, "PROJECT_BUSY", "项目正在处理,请稍后重试");
held.get().add(code);
if (connection != null) connections.get().put(code, connection);
executed = true;
try {
return action.get();
} finally {
held.get().remove(code);
connections.get().remove(code);
if (connections.get().isEmpty()) connections.remove();
if (held.get().isEmpty()) held.remove();
if (connection != null && !lockFunction(connection, "RELEASE_LOCK", name, false))
throw new SQLException("项目锁释放失败");
}
} catch (SQLException error) {
log.warn(
"项目锁连接异常 projectCode={} code=PROJECT_LOCK_UNAVAILABLE sqlState={} errorType={}",
code,
error.getSQLState(),
error.getClass().getSimpleName());
if (executed) markUncertain(code);
throw new BusinessException(503, "PROJECT_LOCK_UNAVAILABLE", "项目锁连接异常,请核对操作结果");
} finally {
lock.unlock();
}
}
private boolean lockFunction(
Connection connection, String function, String name, boolean acquire)
throws SQLException {
try (PreparedStatement statement =
connection.prepareStatement("SELECT " + function + (acquire ? "(?, 3)" : "(?)"))) {
statement.setString(1, name);
try (ResultSet result = statement.executeQuery()) {
return result.next() && result.getInt(1) == 1;
}
}
}
private Project guard(String code) {
return projects == null
? null
: projects.selectOne(
new LambdaQueryWrapper<Project>().eq(Project::getProjectCode, code));
}
private void state(String code, String status) {
if (projects == null) return;
projects.update(
null,
new LambdaUpdateWrapper<Project>()
.eq(Project::getProjectCode, code)
.set(Project::getRepoWriteStatus, status));
}
public void markUncertain(String code) {
uncertain.add(code);
state(code, "REVIEW");
log.warn("仓库写入待核对 projectCode={}", code);
}
public void confirmKnownResult(String code) {
if (!held.get().contains(code)) throw new IllegalStateException("恢复必须持有项目锁");
state(code, "IDLE");
uncertain.remove(code);
log.info("仓库写入结果已核对 projectCode={}", code);
}
private BusinessException blocked() {
return new BusinessException(409, "REMOTE_RESULT_UNKNOWN", "上次仓库写入结果待人工核对,暂不能继续写入");
}
@PreDestroy
public void close() {
if (lockPool != null) lockPool.close();
}
}
@@ -0,0 +1,21 @@
package com.linkerbot.vibemake.service.support;
import com.linkerbot.vibemake.common.BusinessException;
import java.time.Clock;
import java.time.LocalDateTime;
/** 项目、文件和互动服务共用的时间与分页约定。 */
public final class ProjectSupport {
private ProjectSupport() {}
public static LocalDateTime now() {
return LocalDateTime.now(Clock.systemUTC());
}
public static void pageCheck(long page, long size) {
if (page < 1 || page > 100000 || size < 1 || size > 100) {
throw BusinessException.badRequest("分页参数不合法");
}
}
}