安全与效率优化,引入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,156 @@
package com.linkerbot.vibemake.api;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.bean.entity.Project;
import com.linkerbot.vibemake.bean.entity.User;
import com.linkerbot.vibemake.common.Codes;
import com.linkerbot.vibemake.security.TokenService;
import com.linkerbot.vibemake.service.UserService;
import com.linkerbot.vibemake.service.mapper.ProjectMapper;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.*;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.*;
/** 显式启用后只向方舟发送公开示例资料,不访问真实数据库和 Gitea。 */
@EnabledIfEnvironmentVariable(named = "VIBEMAKE_ARK_LIVE_TEST", matches = "true")
@SpringBootTest(properties = {
"spring.datasource.url=jdbc:h2:mem:ai-live;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa", "spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver", "vibemake.ai.enabled=true",
"vibemake.ai.requests-per-minute=120", "vibemake.oss.enabled=false",
"logging.level.root=INFO", "logging.level.com.linkerbot.vibemake=INFO", "debug=false"
})
@ActiveProfiles("test")
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
class AiSearchLiveTest {
@Autowired MockMvc mvc;
@Autowired ObjectMapper json;
@Autowired JdbcTemplate jdbc;
@Autowired ProjectMapper projects;
@Autowired UserService users;
@Autowired TokenService tokens;
@Test void realModelIntroducesMakerAiAndAnswersWithChatHistory() throws Exception {
SchemaSupport.reset(jdbc);
User user = users.login("live-chat@example.invalid");
String token = tokens.issue(user.getId());
JsonNode introduction = chat(token, Map.of("message", "你是谁"));
assertChat(introduction);
assertThat(introduction.path("reply").asText()).containsIgnoringCase("Maker AI").doesNotContain("社区项目助手");
List<Map<String, String>> history = new ArrayList<>(List.of(
Map.of("role", "user", "content", "你是谁"),
Map.of("role", "assistant", "content", introduction.path("reply").asText())));
String question = "我准备使用 Java 编程。请给一个循环输出数字的简短代码示例,不创建项目。";
JsonNode explanation = chat(token, Map.of("message", question, "history", history));
assertChat(explanation);
assertThat(explanation.path("reply").asText()).contains("for");
history.add(Map.of("role", "user", "content", question));
history.add(Map.of("role", "assistant", "content", explanation.path("reply").asText()));
JsonNode followup = chat(token, Map.of("message", "我刚才准备使用什么编程语言?", "history", history));
assertChat(followup);
assertThat(followup.path("reply").asText()).containsIgnoringCase("Java");
assertThat(projects.selectCount(null)).isZero();
}
@ParameterizedTest
@ValueSource(strings = {"pending_create", "pending_fork", "created", "forked"})
void realModelChitChatDoesNotResumeProjectWrites(String context) throws Exception {
SchemaSupport.reset(jdbc);
User user = users.login("live-chat-write@example.invalid");
String question = context.endsWith("create") || context.equals("created") ? "创建教学项目" : "Fork 一个教学项目";
String previousReply = switch (context) {
case "pending_create" -> "请描述想创建的项目,例如用途或名称。";
case "pending_fork" -> "请描述要 Fork 的项目需求,或提供来源项目编码。";
case "created" -> "已创建项目「教学项目」,可以进入工作区继续编辑。";
default -> "已 Fork 为项目「教学项目」,可以进入工作区继续编辑。";
};
JsonNode result = chat(tokens.issue(user.getId()), Map.of("message", "谢谢,今天有点累,想先聊聊天。",
"history", List.of(Map.of("role", "user", "content", question),
Map.of("role", "assistant", "content", previousReply))));
assertChat(result);
assertThat(projects.selectCount(null)).isZero();
}
@Test void realModelFindsProjectsAndChangesTypeAcrossTurns() throws Exception {
SchemaSupport.reset(jdbc);
User user = users.login("live-fixture@example.invalid");
String token = tokens.issue(user.getId());
add(user, "四足教学平台", "QUADRUPED", "四足机器人教学项目。明确支持 ROS2,可用于机器人教学和步态实验。");
add(user, "轮式教学平台", "WHEELED", "轮式机器人教学项目。明确支持 ROS2,可用于机器人教学和移动导航实验。");
add(user, "通用资料", "GENERAL", "机器人基础知识整理。");
String question = "找一个四足机器人项目,必须支持ROS2,最好适合教学。";
JsonNode first = chat(token, Map.of("message", question));
assertType(first, "QUADRUPED");
List<String> codes = new ArrayList<>();
first.path("projects").forEach(card -> codes.add(card.path("project").path("projectCode").asText()));
List<Map<String, String>> history = new ArrayList<>(List.of(
Map.of("role", "user", "content", question),
Map.of("role", "assistant", "content", first.path("reply").asText())));
JsonNode conversation = chat(token, Map.of("message", "谢谢,陪我聊两句吧。", "history", history,
"previousProjectCodes", codes));
assertChat(conversation);
history.add(Map.of("role", "user", "content", "谢谢,陪我聊两句吧。"));
history.add(Map.of("role", "assistant", "content", conversation.path("reply").asText()));
JsonNode second = chat(token, Map.of("message", "改成轮式,其他要求不变。",
"history", history,
"previousProjectCodes", codes));
assertType(second, "WHEELED");
}
private void add(User user, String name, String type, String description) {
Project project = new Project();
project.setProjectCode(Codes.next()); project.setOwnerUserId(user.getId());
project.setName(name); project.setProjectType(type); project.setDescription(description);
project.setGiteaOwner("fixture"); project.setGiteaRepoName(project.getProjectCode());
project.setRepoStatus("READY"); project.setPublishStatus("PUBLISHED");
project.setPublishedCommitSha("a".repeat(40)); project.setDeleted(false);
project.setCreatedAt(LocalDateTime.now()); project.setUpdatedAt(project.getCreatedAt());
project.setPublishedAt(project.getCreatedAt()); projects.insert(project);
}
private JsonNode chat(String token, Object body) throws Exception {
MvcResult started = mvc.perform(post("/api/community/ai/chat").header("Authorization", "Bearer " + token)
.contentType("application/json").content(json.writeValueAsBytes(body)))
.andExpect(status().isOk()).andExpect(request().asyncStarted()).andReturn();
started.getAsyncResult(70000);
MvcResult completed = mvc.perform(asyncDispatch(started)).andExpect(status().isOk()).andReturn();
JsonNode result = null;
for (String line : completed.getResponse().getContentAsString(StandardCharsets.UTF_8).split("\\R")) {
if (!line.startsWith("data:")) continue;
JsonNode event = json.readTree(line.substring(5));
assertThat(event.path("code").asText()).as("上游调用及结果校验").isEqualTo("OK");
if (event.path("data").has("status")) result = event.path("data");
}
assertThat(result).isNotNull();
return result;
}
private void assertType(JsonNode result, String type) {
assertThat(result.path("status").asText()).isEqualTo("MATCHED");
assertThat(result.path("projects").isEmpty()).isFalse();
result.path("projects").forEach(card ->
assertThat(card.path("project").path("projectType").asText()).isEqualTo(type));
}
private void assertChat(JsonNode result) {
assertThat(result.path("status").asText()).isEqualTo("CHAT");
assertThat(result.path("reply").asText()).isNotBlank().hasSizeLessThanOrEqualTo(2000);
assertThat(result.path("projects").isEmpty()).isTrue();
assertThat(result.path("project").isNull()).isTrue();
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,49 @@
package com.linkerbot.vibemake.api;
import static org.assertj.core.api.Assertions.assertThat;
import com.linkerbot.vibemake.security.CorsProperties;
import com.linkerbot.vibemake.security.SecurityConfiguration;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
class CorsProfileTest {
@ParameterizedTest
@CsvSource({
"test, https://dev-vibemake.robotquan.com, https://vibemake.robotquan.com",
"prod, https://vibemake.robotquan.com, https://dev-vibemake.robotquan.com"
})
void profilesAllowOnlyTheirOwnHttpsFrontend(String profile, String allowedOrigin, String otherOrigin)
throws Exception {
StandardEnvironment environment = new StandardEnvironment();
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
for (PropertySource<?> source : loader.load(profile,
new ClassPathResource("application-" + profile + ".yml"))) {
environment.getPropertySources().addFirst(source);
}
CorsProperties properties = Binder.get(environment)
.bind("vibemake.cors", Bindable.of(CorsProperties.class)).get();
assertThat(properties.getAllowedOrigins()).containsExactly(allowedOrigin);
UrlBasedCorsConfigurationSource source =
new SecurityConfiguration().corsConfigurationSource(properties);
CorsConfiguration configuration = source.getCorsConfiguration(
new MockHttpServletRequest("OPTIONS", "/api/workspace/projects"));
assertThat(configuration).isNotNull();
assertThat(configuration.checkOrigin(allowedOrigin)).isEqualTo(allowedOrigin);
assertThat(configuration.checkOrigin(otherOrigin)).isNull();
assertThat(configuration.checkOrigin(allowedOrigin.replace("https://", "http://"))).isNull();
assertThat(configuration.checkOrigin(allowedOrigin + ":8443")).isNull();
assertThat(configuration.checkOrigin("http://localhost:5173")).isNull();
}
}
@@ -0,0 +1,165 @@
package com.linkerbot.vibemake.api;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest(properties = {
"spring.datasource.url=jdbc:h2:mem:cors;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa",
"spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"vibemake.ai.enabled=false",
"vibemake.oss.enabled=false",
"logging.level.org.springframework=WARN"
})
@ActiveProfiles("test")
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
class CorsTest {
private static final String FRONTEND_ORIGIN = "https://dev-vibemake.robotquan.com";
@Autowired MockMvc mvc;
@ParameterizedTest
@CsvSource({
"GET, /api/users/me",
"HEAD, /api/workspace/projects",
"POST, /api/auth/login",
"POST, /api/community/ai/chat",
"PUT, /api/workspace/projects/example/publication",
"PATCH, /api/workspace/projects/example",
"DELETE, /api/workspace/projects/example",
"OPTIONS, /api/workspace/projects"
})
void preflightAllowsSupportedMethodsAndHeadersWithoutAuthentication(String method, String path)
throws Exception {
mvc.perform(options(path)
.header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, method)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS,
"authorization, content-type, accept"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, FRONTEND_ORIGIN))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, containsString(method)))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, containsString("authorization")))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, containsString("content-type")))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, containsString("accept")))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600"))
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
}
@Test
void preflightRunsBeforeBearerTokenValidation() throws Exception {
mvc.perform(options("/api/users/me")
.header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")
.header(HttpHeaders.AUTHORIZATION, "Bearer invalid-test-token"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, FRONTEND_ORIGIN));
}
@Test
void publicResponsesExposeRequestIdAndDownloadHeaders() throws Exception {
mvc.perform(get("/api/project-types").header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value("OK"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, FRONTEND_ORIGIN))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, containsString("X-Request-Id")))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, containsString("Content-Disposition")))
.andExpect(header().exists("X-Request-Id"))
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
}
@Test
void unauthenticatedAndInvalidTokenResponsesKeepCorsHeaders() throws Exception {
mvc.perform(get("/api/users/me").header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.code").value("UNAUTHORIZED"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, FRONTEND_ORIGIN));
mvc.perform(get("/api/project-types")
.header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN)
.header(HttpHeaders.AUTHORIZATION, "Bearer invalid-test-token"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.code").value("UNAUTHORIZED"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, FRONTEND_ORIGIN));
}
@Test
void validationErrorsKeepCorsHeaders() throws Exception {
mvc.perform(post("/api/auth/login")
.header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN)
.contentType(MediaType.APPLICATION_JSON)
.content("{}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value("BAD_REQUEST"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, FRONTEND_ORIGIN));
}
@ParameterizedTest
@ValueSource(strings = {
"https://untrusted.example",
"http://dev-vibemake.robotquan.com",
"https://vibemake.robotquan.com",
"http://localhost:5173",
"https://dev-vibemake.robotquan.com:8443",
"https://dev-vibemake.robotquan.com.untrusted.example",
"null"
})
void unlistedOriginsAreRejectedForPreflightAndActualRequests(String origin) throws Exception {
mvc.perform(options("/api/workspace/projects")
.header(HttpHeaders.ORIGIN, origin)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"))
.andExpect(status().isForbidden())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
mvc.perform(get("/api/project-types").header(HttpHeaders.ORIGIN, origin))
.andExpect(status().isForbidden())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@ParameterizedTest
@CsvSource({"TRACE, Authorization", "POST, X-Unapproved-Header"})
void unsupportedMethodsOrHeadersAreRejected(String method, String requestedHeader)
throws Exception {
mvc.perform(options("/api/workspace/projects")
.header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, method)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, requestedHeader))
.andExpect(status().isForbidden())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void requestsWithoutOriginKeepExistingAuthenticationBehavior() throws Exception {
mvc.perform(get("/api/project-types"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value("OK"))
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
mvc.perform(get("/api/users/me"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.code").value("UNAUTHORIZED"))
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void corsDoesNotExposeNonApiRoutes() throws Exception {
mvc.perform(get("/v3/api-docs").header(HttpHeaders.ORIGIN, FRONTEND_ORIGIN))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
@@ -0,0 +1,39 @@
package com.linkerbot.vibemake.api;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.fork.ForkDeadline;
import com.linkerbot.vibemake.service.fork.GitSnapshotCopier;
import com.linkerbot.vibemake.service.gitea.GiteaClient;
import java.util.List;
import java.util.Map;
/** 业务测试只替换仓库传输,真实 Git/LFS 由独立协议测试覆盖。 */
final class FakeGitSnapshotCopier implements GitSnapshotCopier {
private final FakeGiteaClient gitea;
volatile boolean available = true;
volatile Runnable beforePush;
FakeGitSnapshotCopier(FakeGiteaClient gitea) { this.gitea = gitea; }
@Override public void checkAvailable() {
if (!available) throw new BusinessException(503, "FORK_UNAVAILABLE", "模拟 Git 依赖不可用");
}
@Override
public PreparedSnapshot prepare(GiteaClient.Repository source, String sha, String authorName, String authorCode, ForkDeadline deadline) {
deadline.check();
Map<String, byte[]> files = gitea.snapshot(source, sha);
return new PreparedSnapshot() {
@Override public String push(GiteaClient.Repository target) {
if (beforePush != null) beforePush.run();
deadline.beginWrite();
List<GiteaClient.Change> changes = files.entrySet().stream()
.map(file -> new GiteaClient.Change("create", file.getKey(), null, file.getValue())).toList();
String commit = gitea.commit(target, changes, "Fork vibemake snapshot", authorName, authorCode).commitSha();
deadline.confirmWrite();
return commit;
}
@Override public void close() {}
};
}
}
@@ -0,0 +1,158 @@
package com.linkerbot.vibemake.api;
import com.linkerbot.vibemake.bean.Contracts.*;
import com.linkerbot.vibemake.common.PageResponse;
import com.linkerbot.vibemake.service.gitea.*;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
final class FakeGiteaClient implements GiteaClient {
private static final class RepoData {
Repository repository;
String head;
Map<String, Map<String, byte[]>> snapshots = new HashMap<>();
List<HistoryEntry> history = new ArrayList<>();
}
private final Map<Long, RepoData> repositories = new HashMap<>();
private final AtomicLong sequence = new AtomicLong();
boolean timeoutNextCommit;
boolean timeoutNextCreate;
boolean failNextCreate;
void reset() {
repositories.clear();
timeoutNextCommit = false;
timeoutNextCreate = false;
failNextCreate = false;
}
private String sha() {
return String.format("%040x", sequence.incrementAndGet());
}
private String blob(byte[] data) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(data));
} catch (Exception error) {
throw new IllegalStateException(error);
}
}
private RepoData repo(Repository repository) {
return repositories.get(repository.id());
}
synchronized Map<String, byte[]> snapshot(Repository repository, String sha) {
RepoData data = repo(repository);
Map<String, byte[]> snapshot = data == null ? null : data.snapshots.get(sha);
if (snapshot == null) throw new GiteaFailure(404, "NOT_FOUND", "发布版本不存在", false);
Map<String, byte[]> copy = new TreeMap<>();
snapshot.forEach((name, bytes) -> copy.put(name, bytes.clone()));
return copy;
}
@Override
public synchronized Repository createRepository(String name, boolean initialize) {
if (failNextCreate) {
failNextCreate = false;
throw new GiteaFailure(502, "GITEA_ERROR", "服务拒绝请求", false);
}
RepoData data = new RepoData();
data.repository = new Repository(sequence.incrementAndGet(), "vibemake", name);
repositories.put(data.repository.id(), data);
if (initialize)
commit(
data.repository,
List.of(new Change("create", "README.md", null, "initial".getBytes())),
"Initial commit",
"system",
"system");
if (timeoutNextCreate) {
timeoutNextCreate = false;
throw new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "创建结果未知", true);
}
return data.repository;
}
@Override
public synchronized String head(Repository repository) {
return repo(repository).head;
}
@Override
public synchronized List<TreeEntry> tree(Repository repository, String sha, String path) {
Map<String, byte[]> snapshot = repo(repository).snapshots.get(sha);
if (snapshot == null) throw new GiteaFailure(404, "NOT_FOUND", "版本不存在", false);
String prefix = path.isEmpty() ? "" : path + "/";
Map<String, TreeEntry> entries = new TreeMap<>();
for (Map.Entry<String, byte[]> file : snapshot.entrySet()) {
if (!file.getKey().startsWith(prefix)) continue;
String remainder = file.getKey().substring(prefix.length());
int separator = remainder.indexOf('/');
String name = separator < 0 ? remainder : remainder.substring(0, separator);
String entryPath = prefix + name;
entries.put(
entryPath,
separator < 0
? new TreeEntry(
entryPath,
name,
"file",
file.getValue().length,
blob(file.getValue()))
: new TreeEntry(entryPath, name, "dir", 0, ""));
}
return new ArrayList<>(entries.values());
}
@Override
public synchronized StoredFile file(Repository repository, String sha, String path) {
Map<String, byte[]> snapshot = repo(repository).snapshots.get(sha);
byte[] bytes = snapshot == null ? null : snapshot.get(path);
if (bytes == null) throw new GiteaFailure(404, "NOT_FOUND", "文件不存在", false);
return new StoredFile(path, blob(bytes), bytes.clone());
}
@Override
public synchronized CommitView commit(
Repository repository,
List<Change> changes,
String message,
String authorName,
String authorCode) {
RepoData repo = repo(repository);
Map<String, byte[]> snapshot =
repo.head == null ? new TreeMap<>() : new TreeMap<>(repo.snapshots.get(repo.head));
for (Change change : changes) {
byte[] old = snapshot.get(change.path());
if (change.operation().equals("create") && old != null)
throw new GiteaFailure(409, "GITEA_CONFLICT", "文件已存在", false);
if (!change.operation().equals("create")
&& (old == null || !blob(old).equals(change.blobSha())))
throw new GiteaFailure(409, "GITEA_CONFLICT", "文件版本冲突", false);
if (change.operation().equals("delete")) snapshot.remove(change.path());
else snapshot.put(change.path(), change.bytes().clone());
}
repo.head = sha();
repo.snapshots.put(repo.head, snapshot);
repo.history.addFirst(
new HistoryEntry(repo.head, message, authorName, "2026-10-13T00:00:00Z"));
if (timeoutNextCommit) {
timeoutNextCommit = false;
throw new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "提交结果未知", true);
}
return new CommitView(repo.head, message);
}
@Override
public synchronized PageResponse<HistoryEntry> history(
Repository repository, long page, long size) {
List<HistoryEntry> history = repo(repository).history;
int from = (int) Math.min(history.size(), (page - 1) * size);
int to = (int) Math.min(history.size(), from + size);
return new PageResponse<>(history.subList(from, to), page, size, history.size());
}
}
@@ -0,0 +1,44 @@
package com.linkerbot.vibemake.api;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.oss.OssObjectStore;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
final class FakeOssObjectStore implements OssObjectStore {
final Map<String, byte[]> objects = new ConcurrentHashMap<>();
boolean failNextCopy;
Runnable afterHead;
void reset() {
objects.clear();
failNextCopy = false;
afterHead = null;
}
@Override
public Metadata head(String objectKey) {
byte[] bytes = objects.get(objectKey);
if (bytes == null)
throw new BusinessException(400, "URDF_FILE_MISSING", "URDF 文件未上传完整,请重新上传");
Metadata metadata = new Metadata(bytes.length, Integer.toHexString(Arrays.hashCode(bytes)));
if (afterHead != null) {
Runnable action = afterHead;
afterHead = null;
action.run();
}
return metadata;
}
@Override
public void copy(String sourceKey, String targetKey, String sourceEtag) {
if (failNextCopy) {
failNextCopy = false;
throw new BusinessException(502, "OSS_ERROR", "OSS 资源访问失败,请稍后重试");
}
byte[] bytes = objects.get(sourceKey);
if (!head(sourceKey).etag().equals(sourceEtag)) throw BusinessException.conflict("源文件发生变化");
objects.put(targetKey, bytes.clone());
}
}
@@ -0,0 +1,558 @@
package com.linkerbot.vibemake.api;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.security.CaptchaService;
import com.linkerbot.vibemake.service.config.VibemakeProperties;
import com.linkerbot.vibemake.service.fork.ForkDeadline;
import com.linkerbot.vibemake.service.fork.GitCommandRunner;
import com.linkerbot.vibemake.service.gitea.GiteaClient;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint;
import org.springframework.boot.test.context.*;
import org.springframework.context.annotation.*;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.*;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.*;
@SpringBootTest(
properties = {
"spring.datasource.url=jdbc:h2:mem:live;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa",
"spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"vibemake.ai.enabled=false",
"vibemake.oss.enabled=false",
"logging.level.root=INFO",
"logging.level.org.springframework=WARN"
})
@ActiveProfiles("test")
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
@Import(GiteaLiveTest.Config.class)
@EnabledIfEnvironmentVariable(named = "VIBEMAKE_LIVE_GITEA", matches = "true")
class GiteaLiveTest {
@TestConfiguration
static class Config {
@Bean
@Primary
CaptchaService liveCaptcha(
VibemakeProperties properties,
com.linkerbot.vibemake.common.state.TransientStateStore state) {
return new CaptchaService(properties, state) {
@Override
protected String generateAnswer() {
return "ABCDE";
}
};
}
}
@Autowired MockMvc mvc;
@Autowired ObjectMapper json;
@Autowired JdbcTemplate jdbc;
@Autowired VibemakeProperties config;
@Autowired GitCommandRunner nativeGit;
@Autowired GiteaClient remote;
@TempDir Path gitFixtures;
@BeforeEach
void schema() throws Exception {
SchemaSupport.reset(jdbc);
}
@AfterEach
void removeOnlyRepositoriesCreatedByThisTest() throws Exception {
HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
for (String repo : jdbc.queryForList("SELECT gitea_repo_name FROM project", String.class)) {
if (!repo.matches("p_([0-9a-f]{32}|[0-9abcdefghjkmnpqrstvwxyz]{12})"))
throw new IllegalStateException("拒绝清理非测试仓库");
HttpRequest request =
HttpRequest.newBuilder(
URI.create(
config.getGitea().getBaseUrl()
+ "/api/v1/repos/"
+ config.getGitea().getOwner()
+ "/"
+ repo))
.timeout(Duration.ofSeconds(30))
.header("Authorization", "token " + config.getGitea().getToken())
.DELETE()
.build();
assertThat(http.send(request, HttpResponse.BodyHandlers.discarding()).statusCode())
.isIn(204, 404);
}
}
private MockHttpServletRequestBuilder body(MockHttpServletRequestBuilder request, Object body)
throws Exception {
return request.contentType(MediaType.APPLICATION_JSON)
.content(json.writeValueAsBytes(body));
}
private MockHttpServletRequestBuilder auth(
MockHttpServletRequestBuilder request, String token) {
return request.header("Authorization", "Bearer " + token);
}
private JsonNode perform(MockHttpServletRequestBuilder request, int expected) throws Exception {
MvcResult result = mvc.perform(request).andReturn();
JsonNode response = json.readTree(result.getResponse().getContentAsByteArray());
assertThat(result.getResponse().getStatus())
.withFailMessage(
"请求失败 code=%s requestId=%s",
response.path("code").asText(), response.path("requestId").asText())
.isEqualTo(expected);
return response.path("data");
}
private String login(String email) throws Exception {
String captcha = perform(get("/api/auth/captcha"), 200).path("captchaCode").asText();
return perform(
body(
post("/api/auth/login"),
Map.of(
"email",
email,
"captchaCode",
captcha,
"captchaAnswer",
"ABCDE")),
200)
.path("token")
.asText();
}
@Test
void realSnapshotForkPreservesLargeCadGitlinksSymlinksAndLfsWithoutUnpublishedHistory()
throws Exception {
String owner = login("live-snapshot-owner@example.invalid");
String other = login("live-snapshot-fork@example.invalid");
String source =
perform(
body(
auth(post("/api/workspace/projects"), owner),
Map.of(
"name",
"HyperDog OpenFish 类型快照联调",
"projectType",
"GENERAL")),
200)
.path("projectCode")
.asText();
String original =
perform(auth(get("/api/workspace/projects/" + source + "/tree"), owner), 200)
.path("commitSha")
.asText();
Path staging = Files.createDirectory(gitFixtures.resolve("fixture.git"));
String base = config.getGitea().getBaseUrl().replaceAll("/+$", "");
String url = base + "/" + config.getGitea().getOwner() + "/p_" + source + ".git";
String basic =
Base64.getEncoder()
.encodeToString(
(remote.authenticatedUsername()
+ ":"
+ config.getGitea().getToken())
.getBytes(StandardCharsets.UTF_8));
Map<String, String> settings = new LinkedHashMap<>();
settings.put("http." + base + "/.extraHeader", "Authorization: Basic " + basic);
settings.put("lfs.url", url + "/info/lfs");
settings.put("lfs.pushurl", url + "/info/lfs");
settings.put("lfs.basictransfersonly", "true");
fixtureGit(staging, settings, "init", "--bare", "--quiet");
fixtureGit(staging, settings, "remote", "add", "origin", url);
fixtureGit(staging, settings, "fetch", "--quiet", "origin", "refs/heads/main");
fixtureGit(staging, settings, "read-tree", original);
String ordinary =
fixtureBlob(staging, settings, "published".getBytes(StandardCharsets.UTF_8));
String cad = fixtureBlob(staging, settings, new byte[13 * 1024 * 1024]);
String link = fixtureBlob(staging, settings, "README.md".getBytes(StandardCharsets.UTF_8));
byte[] lfsBytes = new byte[256 * 1024];
new Random(42).nextBytes(lfsBytes);
String oid =
HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(lfsBytes));
Path object =
staging.resolve(
"lfs/objects/"
+ oid.substring(0, 2)
+ "/"
+ oid.substring(2, 4)
+ "/"
+ oid);
Files.createDirectories(object.getParent());
Files.write(object, lfsBytes);
String pointer =
fixtureBlob(
staging,
settings,
("version https://git-lfs.github.com/spec/v1\noid sha256:"
+ oid
+ "\nsize "
+ lfsBytes.length
+ "\n")
.getBytes(StandardCharsets.UTF_8));
String attributes =
fixtureBlob(
staging,
settings,
"model.bin filter=lfs diff=lfs merge=lfs -text\n"
.getBytes(StandardCharsets.UTF_8));
Map<String, String> files = new LinkedHashMap<>();
files.put("README.md", "100644," + ordinary);
files.put("说明/示例.txt", "100644," + ordinary);
files.put("run.sh", "100755," + ordinary);
files.put("SOLIDWORKS_FILES/Assembly_#1.SLDASM", "100644," + cad);
files.put("readme-link", "120000," + link);
files.put("model.bin", "100644," + pointer);
files.put(".gitattributes", "100644," + attributes);
for (String path :
List.of(
"uros/drive_base",
"uros/micro-ROS-Agent",
"uros/micro_ros_msgs",
"uros_pkg/src/micro_ros_setup"))
files.put(path, "160000," + "a".repeat(40));
for (Map.Entry<String, String> file : files.entrySet()) {
String[] modeAndHash = file.getValue().split(",");
fixtureGit(
staging,
settings,
"update-index",
"--add",
"--cacheinfo",
modeAndHash[0],
modeAndHash[1],
file.getKey());
}
String tree = fixtureGit(staging, settings, "write-tree");
String publication =
fixtureGit(
staging,
settings,
"commit-tree",
tree,
"-p",
original,
"-m",
"Special Git/LFS fixture");
fixtureGit(staging, settings, "update-ref", "refs/heads/fixture", publication);
fixtureGit(staging, settings, "lfs", "push", "--all", "origin", "refs/heads/fixture");
fixtureGit(
staging, settings, "push", "--quiet", "origin", publication + ":refs/heads/main");
perform(
body(
auth(put("/api/workspace/projects/" + source + "/publication"), owner),
Map.of("commitSha", publication)),
200);
perform(
body(
auth(post("/api/workspace/projects/" + source + "/commits"), owner),
Map.of(
"expectedCommitSha",
publication,
"message",
"unpublished change",
"changes",
List.of(
Map.of(
"action",
"UPDATE_FILE",
"path",
"README.md",
"content",
"private unpublished")))),
200);
Set<String> copies = new HashSet<>();
for (String token : List.of(owner, other)) {
JsonNode fork =
perform(
body(
auth(
post("/api/community/projects/" + source + "/forks"),
token),
Map.of("name", "快照联调副本", "publishedCommitSha", publication)),
200);
String code = fork.path("projectCode").asText();
assertThat(copies.add(code)).isTrue();
assertThat(fork.path("repoStatus").asText()).isEqualTo("READY");
assertThat(fork.path("sourceCommitSha").asText()).isEqualTo(publication);
GiteaClient.Repository repository =
new GiteaClient.Repository(0, config.getGitea().getOwner(), "p_" + code);
JsonNode metadata = readRepository("p_" + code, "");
assertThat(metadata.path("empty").asBoolean())
.as(
"Gitea metadata empty; defaultBranch=%s",
metadata.path("default_branch").asText())
.isFalse();
String head =
readRepository("p_" + code, "/branches/main")
.path("commit")
.path("id")
.asText();
JsonNode commit = readRepository("p_" + code, "/git/commits/" + head);
assertThat(commit.path("parents").isArray()).isTrue();
assertThat(commit.path("parents").isEmpty()).isTrue();
String copyRemote = "copy" + copies.size();
fixtureGit(
staging,
settings,
"remote",
"add",
copyRemote,
base + "/" + config.getGitea().getOwner() + "/p_" + code + ".git");
fixtureGit(
staging,
settings,
"fetch",
"--quiet",
"--no-tags",
copyRemote,
"refs/heads/main");
assertThat(fixtureGit(staging, settings, "rev-parse", head + "^{tree}"))
.isEqualTo(tree);
assertThat(remote.history(repository, 1, 20).total()).isEqualTo(1);
JsonNode entries =
readRepository("p_" + code, "/git/trees/" + head + "?recursive=true");
assertThat(entries.path("tree").findValuesAsText("mode"))
.contains("100755", "120000", "160000");
assertThat(
perform(
auth(
get("/api/workspace/projects/"
+ code
+ "/files")
.param("path", "README.md"),
token),
200)
.path("content")
.asText())
.isEqualTo("published");
mvc.perform(
auth(
get("/api/workspace/projects/" + code + "/files")
.param("path", "SOLIDWORKS_FILES/Assembly_#1.SLDASM")
.param("download", "true"),
token))
.andExpect(status().is(413));
}
}
private String fixtureGit(Path staging, Map<String, String> settings, String... args) {
GitCommandRunner.Result result =
nativeGit.run(
staging,
new ForkDeadline(Duration.ofMinutes(2)),
"live-fixture",
settings,
Map.of(
"GIT_AUTHOR_NAME",
"Fixture",
"GIT_AUTHOR_EMAIL",
"fixture@users.vibemake.invalid",
"GIT_COMMITTER_NAME",
"Fixture",
"GIT_COMMITTER_EMAIL",
"fixture@users.vibemake.invalid"),
args);
assertThat(result.exitCode()).as("live Git fixture command completed").isZero();
return result.output();
}
private String fixtureBlob(Path staging, Map<String, String> settings, byte[] bytes)
throws Exception {
Path input = Files.createTempFile(gitFixtures, "blob-", ".bin");
Files.write(input, bytes);
return fixtureGit(staging, settings, "hash-object", "-w", input.toString());
}
private JsonNode readRepository(String repository, String suffix) throws Exception {
String url =
config.getGitea().getBaseUrl().replaceAll("/+$", "")
+ "/api/v1/repos/"
+ config.getGitea().getOwner()
+ "/"
+ repository
+ suffix;
HttpRequest request =
HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(30))
.header("Authorization", "token " + config.getGitea().getToken())
.GET()
.build();
HttpResponse<byte[]> response =
HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() != 200) {
String diagnostic =
new String(response.body(), StandardCharsets.UTF_8)
.replace(config.getGitea().getToken(), "[redacted]")
.replaceAll(
"(?im)(Authorization|Cookie|Set-Cookie):[^\\r\\n]*",
"$1: [redacted]");
if (diagnostic.length() > 18000) diagnostic = diagnostic.substring(0, 18000);
assertThat(response.statusCode())
.withFailMessage("Fixture Gitea response: %s", diagnostic)
.isEqualTo(200);
}
assertThat(response.statusCode()).isEqualTo(200);
return json.readTree(response.body());
}
@Test
void realOrganizationRepositoryCommitPublishUploadAndSnapshotFork() throws Exception {
String owner = login("live-owner@example.invalid"),
other = login("live-fork@example.invalid");
String code =
perform(
body(
auth(post("/api/workspace/projects"), owner),
Map.of("name", "集成测试临时项目", "projectType", "GENERAL")),
200)
.path("projectCode")
.asText();
String a =
perform(auth(get("/api/workspace/projects/" + code + "/tree"), owner), 200)
.path("commitSha")
.asText();
JsonNode before =
perform(
auth(
get("/api/workspace/projects/" + code + "/files")
.param("path", "README.md"),
owner),
200);
perform(
body(
auth(put("/api/workspace/projects/" + code + "/publication"), owner),
Map.of("commitSha", a)),
200);
JsonNode b =
perform(
body(
auth(post("/api/workspace/projects/" + code + "/commits"), owner),
Map.of(
"expectedCommitSha",
a,
"message",
"集成验证多文件提交",
"changes",
List.of(
Map.of(
"action",
"UPDATE_FILE",
"path",
"README.md",
"content",
"unpublished"),
Map.of("action", "CREATE_DIRECTORY", "path", "空目录"),
Map.of(
"action",
"CREATE_FILE",
"path",
"源码/hello world.txt",
"content",
"你好")))),
200);
assertThat(
perform(
get("/api/community/projects/" + code + "/files")
.param("path", "README.md"),
200)
.path("content")
.asText())
.isEqualTo(before.path("content").asText());
byte[] binary = {0, 1, 2, 3, 4};
MockMultipartFile upload =
new MockMultipartFile("files", "part.bin", "application/octet-stream", binary);
JsonNode c =
perform(
auth(
multipart("/api/workspace/projects/" + code + "/uploads/commit")
.file(upload)
.param("message", "验证二进制")
.param("expectedCommitSha", b.path("commitSha").asText())
.param("directory", "模型"),
owner),
200);
mvc.perform(
auth(
get("/api/workspace/projects/" + code + "/files")
.param("path", "模型/part.bin")
.param("download", "true"),
owner))
.andExpect(status().isOk())
.andExpect(content().bytes(binary));
perform(
body(
auth(put("/api/workspace/projects/" + code + "/publication"), owner),
Map.of("commitSha", c.path("commitSha").asText())),
200);
JsonNode fork =
perform(
body(
auth(post("/api/community/projects/" + code + "/forks"), other),
Map.of(
"name",
"集成测试临时副本",
"publishedCommitSha",
c.path("commitSha").asText())),
200);
String copy = fork.path("projectCode").asText();
readRepository(
"p_" + copy,
"/contents/%E6%BA%90%E7%A0%81/hello%20world.txt?ref="
+ readRepository("p_" + copy, "/branches/main")
.path("commit")
.path("id")
.asText());
assertThat(
perform(
auth(
get("/api/workspace/projects/" + copy + "/files")
.param("path", "源码/hello world.txt"),
other),
200)
.path("content")
.asText())
.isEqualTo("你好");
mvc.perform(
auth(
get("/api/workspace/projects/" + copy + "/files")
.param("path", "模型/part.bin")
.param("download", "true"),
other))
.andExpect(status().isOk())
.andExpect(content().bytes(binary));
assertThat(
perform(
auth(
get("/api/workspace/projects/" + code + "/commits"),
owner),
200)
.path("total")
.asLong())
.isGreaterThanOrEqualTo(3);
perform(auth(delete("/api/workspace/projects/" + code + "/publication"), owner), 200);
perform(get("/api/community/projects/" + code), 404);
perform(auth(get("/api/workspace/projects/" + copy + "/tree"), other), 200);
}
}
@@ -0,0 +1,91 @@
package com.linkerbot.vibemake.api;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.common.state.TransientStateStore;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.*;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest(
properties = {
"spring.datasource.url=jdbc:h2:mem:http-safety;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa",
"spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"vibemake.ai.enabled=false",
"vibemake.oss.enabled=false",
"vibemake.limits.enabled=true",
"vibemake.limits.per-minute.captcha=1",
"vibemake.limits.json-bytes=64",
"logging.level.root=WARN"
})
@ActiveProfiles("test")
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
@Import(WorkflowTest.Config.class)
class HttpSafetyTest {
private static final String ORIGIN = "https://dev-vibemake.robotquan.com";
@Autowired MockMvc mvc;
@MockitoSpyBean TransientStateStore state;
@AfterEach
void resetSpy() {
reset(state);
}
@Test
void corsAndRetryAfterSurviveLimitErrorsAndPreflightDoesNotCount() throws Exception {
mvc.perform(
options("/api/auth/captcha")
.header("Origin", ORIGIN)
.header("Access-Control-Request-Method", "GET"))
.andExpect(status().isOk());
mvc.perform(get("/api/auth/captcha").header("Origin", ORIGIN))
.andExpect(status().isOk())
.andExpect(header().string("Cache-Control", "no-store"));
mvc.perform(get("/api/auth/captcha").header("Origin", ORIGIN))
.andExpect(status().isTooManyRequests())
.andExpect(jsonPath("$.code").value("RATE_LIMITED"))
.andExpect(header().exists("Retry-After"))
.andExpect(header().string("Access-Control-Allow-Origin", ORIGIN))
.andExpect(header().exists("X-Request-Id"));
}
@Test
void redisFailureInAuthenticationReturns503WithCorsAndRequestId() throws Exception {
doThrow(new BusinessException(503, "REDIS_UNAVAILABLE", "安全状态服务不可用"))
.when(state)
.get(anyString());
mvc.perform(
get("/api/users/me")
.header("Origin", ORIGIN)
.header("Authorization", "Bearer " + "a".repeat(43)))
.andExpect(status().isServiceUnavailable())
.andExpect(jsonPath("$.code").value("REDIS_UNAVAILABLE"))
.andExpect(header().string("Access-Control-Allow-Origin", ORIGIN))
.andExpect(header().exists("X-Request-Id"));
}
@Test
void jsonSizeFailuresRemain413WithJsonAndCors() throws Exception {
mvc.perform(
post("/api/auth/login")
.header("Origin", ORIGIN)
.contentType(MediaType.APPLICATION_JSON)
.content("{\"email\":\"" + "x".repeat(100) + "\"}"))
.andExpect(status().isPayloadTooLarge())
.andExpect(jsonPath("$.code").value("REQUEST_TOO_LARGE"))
.andExpect(header().string("Access-Control-Allow-Origin", ORIGIN));
}
}
@@ -0,0 +1,19 @@
package com.linkerbot.vibemake.api;
import static org.assertj.core.api.Assertions.*;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.io.ClassPathResource;
class OssProfileTest {
@Test
void environmentProfilesKeepCoverDirectoriesSeparate() throws IOException {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
assertThat(loader.load("test", new ClassPathResource("application-test.yml")).getFirst()
.getProperty("vibemake.oss.root-directory")).isEqualTo("vibemake_dev");
assertThat(loader.load("prod", new ClassPathResource("application-prod.yml")).getFirst()
.getProperty("vibemake.oss.root-directory")).isEqualTo("vibemake");
}
}
@@ -0,0 +1,290 @@
package com.linkerbot.vibemake.api;
import static org.assertj.core.api.Assertions.*;
import com.linkerbot.vibemake.bean.Contracts.ProjectView;
import com.linkerbot.vibemake.bean.entity.User;
import com.linkerbot.vibemake.common.PageResponse;
import com.linkerbot.vibemake.service.*;
import com.linkerbot.vibemake.service.admin.AdminManagementService;
import com.linkerbot.vibemake.service.support.ProjectActors;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.*;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import java.lang.management.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
@SpringBootTest(
properties = {
"spring.datasource.url=jdbc:h2:mem:query-efficiency;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa",
"spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"vibemake.ai.enabled=false",
"vibemake.oss.enabled=false",
"logging.level.root=WARN"
})
@ActiveProfiles("test")
@Import({WorkflowTest.Config.class, QueryEfficiencyTest.Config.class})
class QueryEfficiencyTest {
private static final String MYSQL_URL = System.getenv("BENCHMARK_MYSQL_URL");
private static final String DATABASE =
"vibemake_benchmark_" + UUID.randomUUID().toString().replace("-", "");
private static boolean databaseCreated;
@DynamicPropertySource
static void isolatedMysql(DynamicPropertyRegistry registry) throws Exception {
if (MYSQL_URL == null || MYSQL_URL.isBlank()) return;
if (!MYSQL_URL.startsWith("jdbc:mysql:"))
throw new IllegalArgumentException("基准测试只接受 MySQL URL");
try (java.sql.Connection connection = bootstrapConnection();
java.sql.Statement statement = connection.createStatement()) {
if (!"MySQL".equals(connection.getMetaData().getDatabaseProductName()))
throw new IllegalStateException("需要 MySQL");
statement.execute(
"CREATE DATABASE "
+ DATABASE
+ " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
databaseCreated = true;
}
String plain = MYSQL_URL.split("\\?", 2)[0];
String isolated =
plain.substring(0, plain.lastIndexOf('/') + 1)
+ DATABASE
+ (MYSQL_URL.contains("?") ? "?" + MYSQL_URL.split("\\?", 2)[1] : "");
registry.add("spring.datasource.url", () -> isolated);
registry.add("spring.datasource.username", () -> System.getenv("BENCHMARK_MYSQL_USERNAME"));
registry.add(
"spring.datasource.password",
() -> System.getenv().getOrDefault("BENCHMARK_MYSQL_PASSWORD", ""));
registry.add("spring.datasource.driver-class-name", () -> "com.mysql.cj.jdbc.Driver");
}
private static java.sql.Connection bootstrapConnection() throws java.sql.SQLException {
return java.sql.DriverManager.getConnection(
MYSQL_URL,
System.getenv("BENCHMARK_MYSQL_USERNAME"),
System.getenv().getOrDefault("BENCHMARK_MYSQL_PASSWORD", ""));
}
@AfterAll
static void removeOnlyIsolatedDatabase() throws Exception {
if (!databaseCreated) return;
try (java.sql.Connection connection = bootstrapConnection();
java.sql.Statement statement = connection.createStatement()) {
statement.execute("DROP DATABASE " + DATABASE);
}
}
private void resetSchema() throws Exception {
if (!databaseCreated) {
SchemaSupport.reset(jdbc);
return;
}
// 连接目标必须是本次创建的随机临时库,禁止对外部配置指定的业务库执行 DDL。
try (java.sql.Connection connection =
java.util.Objects.requireNonNull(jdbc.getDataSource()).getConnection()) {
assertThat(connection.getCatalog()).isEqualTo(DATABASE);
}
for (String table :
List.of(
"project_import_task",
"project_like",
"project_comment",
"project",
"sys_user")) jdbc.execute("DROP TABLE IF EXISTS " + table);
java.nio.file.Path docs = java.nio.file.Path.of("../docs");
if (!java.nio.file.Files.exists(docs)) docs = java.nio.file.Path.of("docs");
for (String name : List.of("database.md", "admin-database.md")) {
java.util.regex.Matcher tables =
java.util.regex.Pattern.compile("CREATE TABLE [\\s\\S]*?;")
.matcher(java.nio.file.Files.readString(docs.resolve(name)));
while (tables.find()) jdbc.execute(tables.group());
}
}
@TestConfiguration
static class Config {
@Bean
SqlCounter sqlCounter() {
return new SqlCounter();
}
}
@Intercepts(
@Signature(
type = StatementHandler.class,
method = "prepare",
args = {java.sql.Connection.class, Integer.class}))
static class SqlCounter implements Interceptor {
final AtomicInteger count = new AtomicInteger();
@Override
public Object intercept(Invocation invocation) throws Throwable {
if (((StatementHandler) invocation.getTarget())
.getBoundSql()
.getSql()
.stripLeading()
.toUpperCase(Locale.ROOT)
.startsWith("SELECT")) count.incrementAndGet();
return invocation.proceed();
}
}
@Autowired SqlCounter sql;
@Autowired JdbcTemplate jdbc;
@Autowired ProjectService projects;
@Autowired UserService users;
@Autowired InteractionService interactions;
@Autowired AdminManagementService management;
private User owner;
@BeforeEach
void seed() throws Exception {
resetSchema();
owner = users.login("efficiency@example.invalid");
for (int index = 1; index <= 21; index++) {
String code = String.format("%012d", index);
jdbc.update(
"INSERT INTO"
+ " project(project_code,owner_user_id,name,description,project_type,gitea_owner,gitea_repo_name,gitea_repo_id,repo_status,publish_status,published_commit_sha,published_at,source_project_id,created_at,updated_at)"
+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
code,
owner.getId(),
"项目" + index,
"性能验证",
"GENERAL",
"vibemake",
"p_" + code,
(long) index,
"READY",
"PUBLISHED",
"a".repeat(40),
java.sql.Timestamp.valueOf("2026-01-01 00:00:00"),
index == 1 ? null : 1L);
if (index > 1) {
jdbc.update(
"INSERT INTO project_like(project_id,user_id,created_at)"
+ " VALUES(?,?,CURRENT_TIMESTAMP)",
index,
owner.getId());
jdbc.update(
"INSERT INTO"
+ " project_import_task(task_code,project_code,operator_user_code,source_repository_id,source_repository_url,source_default_branch,status,phase,warnings_json,created_at,updated_at)"
+ " VALUES(?,?,?,?,?,?,?,?,'[]',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
String.format("%032d", index),
code,
owner.getUserCode(),
(long) index,
"https://github.com/example/r" + index,
"main",
"SUCCEEDED",
"READY");
}
}
for (int index = 1; index <= 20; index++)
jdbc.update(
"INSERT INTO"
+ " project_comment(comment_code,project_id,user_id,content,deleted,created_at,updated_at)"
+ " VALUES(?,2,?,?,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
String.format("%032d", index),
owner.getId(),
"评论" + index);
for (int index = 1; index <= 19; index++)
users.login("efficiency-" + index + "@example.invalid");
sql.count.set(0);
}
@Test
void batchesKeepResponsesAndBoundQueryCounts() {
PageResponse<ProjectView> result = projects.list(null, null, null, 1, 20, owner.getId());
int projectQueries = sql.count.getAndSet(0);
assertThat(result.items()).hasSize(20);
assertThat(result.items())
.allSatisfy(
view -> {
assertThat(view.owner().userCode()).isEqualTo(owner.getUserCode());
assertThat(view.likeCount()).isEqualTo(1);
assertThat(view.liked()).isTrue();
assertThat(view.sourceProjectCode()).isEqualTo("000000000001");
assertThat(view.sourceRepositoryUrl())
.startsWith("https://github.com/example/");
});
assertThat(interactions.list("000000000002", 1, 20).items()).hasSize(20);
int commentQueries = sql.count.getAndSet(0);
try (ProjectActors.Scope scope =
ProjectActors.enter(new ProjectActors.AdminActor(owner.getUserCode(), "管理员"))) {
assertThat(management.users(1, 20, null, null, null, null, null).items())
.hasSize(20)
.anySatisfy(
view -> {
assertThat(view.userCode()).isEqualTo(owner.getUserCode());
assertThat(view.projectCount()).isEqualTo(21);
});
}
int userQueries = sql.count.getAndSet(0);
System.out.printf(
"QUERY_COUNTS projects=%d comments=%d users=%d%n",
projectQueries, commentQueries, userQueries);
if (!Boolean.getBoolean("vibemake.benchmark.baseline")) {
assertThat(projectQueries).isLessThanOrEqualTo(8);
assertThat(commentQueries).isLessThanOrEqualTo(4);
assertThat(userQueries).isLessThanOrEqualTo(3);
}
}
@Test
void repeatableListBenchmark() throws Exception {
for (int i = 0; i < 15; i++) projects.list(null, null, null, 1, 20, owner.getId());
benchmark(1);
benchmark(4);
}
private void benchmark(int concurrency) throws Exception {
System.gc();
Thread.sleep(100);
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans())
if (pool.getType() == MemoryType.HEAP) pool.resetPeakUsage();
long[] samples = new long[100];
sql.count.set(0);
try (java.util.concurrent.ExecutorService pool =
java.util.concurrent.Executors.newFixedThreadPool(concurrency)) {
List<java.util.concurrent.Future<?>> tasks = new ArrayList<>();
for (int i = 0; i < samples.length; i++) {
int sample = i;
tasks.add(
pool.submit(
() -> {
long start = System.nanoTime();
projects.list(null, null, null, 1, 20, owner.getId());
samples[sample] = System.nanoTime() - start;
}));
}
for (java.util.concurrent.Future<?> task : tasks) task.get();
}
Arrays.sort(samples);
long heapPoolPeaks =
ManagementFactory.getMemoryPoolMXBeans().stream()
.filter(pool -> pool.getType() == MemoryType.HEAP)
.mapToLong(pool -> pool.getPeakUsage().getUsed())
.sum();
System.out.printf(
Locale.ROOT,
"LIST_BENCHMARK samples=100 concurrency=%d sqlPerRequest=%d p95Ms=%.3f"
+ " heapPoolPeakBytes=%d%n",
concurrency,
sql.count.get() / samples.length,
samples[94] / 1_000_000.0,
heapPoolPeaks);
}
}
@@ -0,0 +1,179 @@
package com.linkerbot.vibemake.api;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.bean.entity.User;
import com.linkerbot.vibemake.common.SecurityHashes;
import com.linkerbot.vibemake.common.state.TransientStateStore;
import com.linkerbot.vibemake.security.CaptchaService;
import com.linkerbot.vibemake.security.TokenService;
import com.linkerbot.vibemake.service.UserService;
import com.linkerbot.vibemake.service.config.VibemakeProperties;
import com.linkerbot.vibemake.service.config.RedisStateProperties;
import com.linkerbot.vibemake.service.state.RedisStateStore;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.*;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import java.time.Duration;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
@SpringBootTest(
properties = {
"vibemake.redis.real-test=true",
"vibemake.limits.enabled=false",
"vibemake.admin.worker-enabled=false",
"spring.datasource.url=jdbc:h2:mem:redis-live;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa",
"spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"spring.data.redis.host=${REDIS_TEST_HOST}",
"spring.data.redis.port=${REDIS_TEST_PORT:6379}",
"spring.data.redis.username=${REDIS_TEST_USERNAME:}",
"spring.data.redis.password=${REDIS_TEST_PASSWORD:}",
"spring.data.redis.database=${REDIS_TEST_DATABASE:0}",
"spring.data.redis.ssl.enabled=${REDIS_TEST_SSL_ENABLED:false}",
"vibemake.redis.key-prefix=vibemake:test:redis-live-${random.uuid}",
"logging.level.org.springframework=WARN"
})
@ActiveProfiles("test")
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
@Import(WorkflowTest.Config.class)
@EnabledIfEnvironmentVariable(named = "REDIS_TEST_HOST", matches = ".+")
class RedisLiveTest {
@Autowired TransientStateStore state;
@Autowired StringRedisTemplate redis;
@Autowired RedisStateProperties namespace;
@Autowired VibemakeProperties properties;
@Autowired ObjectMapper json;
@Autowired TokenService tokens;
@Autowired CaptchaService captcha;
@Autowired UserService users;
@Autowired JdbcTemplate jdbc;
@Autowired MockMvc mvc;
@BeforeEach
void schema() throws Exception {
SchemaSupport.reset(jdbc);
}
@AfterEach
void cleanOnlyThisTestNamespace() {
assertThat(namespace.getKeyPrefix()).startsWith("vibemake:test:redis-live-");
try (Cursor<String> cursor =
redis.scan(
ScanOptions.scanOptions()
.match(namespace.prefix() + "*")
.count(100)
.build())) {
while (cursor.hasNext()) redis.delete(cursor.next());
}
}
@Test
void ttlAtomicConsumptionIsolationAndReconnection() throws Exception {
assertThat(state).isInstanceOf(RedisStateStore.class);
state.verify();
assertThat(state.putIfAbsent("ttl", "once", Duration.ofMillis(80))).isTrue();
assertThat(state.putIfAbsent("ttl", "other", Duration.ofMinutes(1))).isFalse();
Thread.sleep(120);
assertThat(state.get("ttl")).isNull();
state.putIfAbsent("consume", "only", Duration.ofMinutes(1));
AtomicInteger accepted = new AtomicInteger();
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 30; i++)
pool.submit(
() -> {
if ("only".equals(state.consume("consume"))) accepted.incrementAndGet();
});
}
assertThat(accepted.get()).isEqualTo(1);
AtomicInteger maximum = new AtomicInteger();
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 40; i++)
pool.submit(
() ->
maximum.accumulateAndGet(
(int)
state.increment(
"counter",
Duration.ofSeconds(30),
false)
.count(),
Math::max));
}
assertThat(maximum.get()).isEqualTo(40);
RedisStateProperties other = new RedisStateProperties();
other.setKeyPrefix(namespace.getKeyPrefix());
other.setApplication("admin");
assertThat(new RedisStateStore(redis, other).get("counter")).isNull();
RedisStandaloneConfiguration configuration =
new RedisStandaloneConfiguration(
System.getenv("REDIS_TEST_HOST"),
Integer.parseInt(System.getenv().getOrDefault("REDIS_TEST_PORT", "6379")));
configuration.setUsername(System.getenv("REDIS_TEST_USERNAME"));
configuration.setPassword(System.getenv().getOrDefault("REDIS_TEST_PASSWORD", ""));
configuration.setDatabase(
Integer.parseInt(System.getenv().getOrDefault("REDIS_TEST_DATABASE", "0")));
org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration
.LettuceClientConfigurationBuilder
client =
org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration
.builder()
.commandTimeout(Duration.ofSeconds(1));
if (Boolean.parseBoolean(System.getenv("REDIS_TEST_SSL_ENABLED"))) client.useSsl();
LettuceConnectionFactory factory =
new LettuceConnectionFactory(configuration, client.build());
try {
factory.afterPropertiesSet();
factory.start();
StringRedisTemplate replacement = new StringRedisTemplate(factory);
assertThat(new RedisStateStore(replacement, namespace).get("counter")).isEqualTo("40");
} finally {
factory.destroy();
}
}
@Test
void sessionsCaptchaRevocationAndDisabledUsersUseRealRedis() throws Exception {
User user = users.login("redis-test@example.invalid");
String token = tokens.issue(user.getId(), user.getSessionVersion());
assertThat(redis.hasKey(namespace.prefix() + "session:" + token)).isFalse();
assertThat(redis.hasKey(namespace.prefix() + "session:" + SecurityHashes.sha256(token)))
.isTrue();
TokenService replacement =
new TokenService(properties, new RedisStateStore(redis, namespace), json);
assertThat(replacement.resolve(token)).isEqualTo(user.getId());
mvc.perform(get("/api/users/me").header("Authorization", "Bearer " + token))
.andExpect(status().isOk());
String code = captcha.issue().captchaCode();
captcha.verify(code, "ABCDE");
assertThatThrownBy(() -> captcha.verify(code, "ABCDE"))
.isInstanceOf(com.linkerbot.vibemake.common.BusinessException.class);
jdbc.update(
"UPDATE sys_user SET status='DISABLED', session_version=session_version+1 WHERE"
+ " id=?",
user.getId());
mvc.perform(get("/api/users/me").header("Authorization", "Bearer " + token))
.andExpect(status().isUnauthorized());
jdbc.update("UPDATE sys_user SET status='ACTIVE' WHERE id=?", user.getId());
mvc.perform(get("/api/users/me").header("Authorization", "Bearer " + token))
.andExpect(status().isUnauthorized());
replacement.revoke(token);
assertThat(tokens.resolve(token)).isNull();
}
}
@@ -0,0 +1,150 @@
package com.linkerbot.vibemake.api;
import static org.assertj.core.api.Assertions.*;
import com.linkerbot.vibemake.service.config.OssProperties;
import com.linkerbot.vibemake.service.oss.OssResourcePaths;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/** 执行数据库文档中的 SQL;仅将 MySQL JOIN UPDATE、排序规则和正则语法适配到 H2。 */
class ResourcePathMigrationTest {
private static final String ROOT = "vibemake_dev";
private static final String BASE = "https://linkerbot.oss-cn-beijing.aliyuncs.com";
private static final String CODE = "1".repeat(12);
private static final String COVER = "/project-covers/" + "1".repeat(32) + "/20261019/" + "a".repeat(32) + ".png";
private static final String PREFIX = "/urdf/" + CODE + "/" + "a".repeat(32) + "/";
private static final String MAIN = PREFIX + "urdf/机械 臂 #?%+.URDF";
private SingleConnectionDataSource source;
private JdbcTemplate jdbc;
private String document;
private OssResourcePaths paths;
@BeforeEach
void prepare() throws Exception {
source = new SingleConnectionDataSource("jdbc:h2:mem:migration;MODE=MySQL", "sa", "", true);
jdbc = new JdbcTemplate(source);
jdbc.execute("CREATE TABLE project (project_code VARCHAR(32) PRIMARY KEY, cover_url VARCHAR(2048),"
+ " urdf_main_object_key VARCHAR(512) NOT NULL, urdf_prefix VARCHAR(512) NOT NULL)");
document = Files.readString(Path.of("../docs/database.md"));
OssProperties oss = new OssProperties();
oss.setRootDirectory(ROOT);
oss.setPublicBaseUrl(BASE);
paths = new OssResourcePaths(oss);
}
@AfterEach
void close() {
source.destroy();
}
@Test
void migrationIsIdempotentAndPreservesExternalUrlsAndObjectLocations() {
insert(CODE, BASE + "/" + ROOT + COVER, ROOT + MAIN, ROOT + PREFIX);
insert("2".repeat(12), "https://external.example.com" + COVER, "", "");
insert("3".repeat(12), BASE + "/" + ROOT + COVER + "?version=2", "", "");
insert("4".repeat(12), BASE + "/" + ROOT + COVER + "#preview", "", "");
insert("5".repeat(12), COVER, "/urdf/already/a.urdf", "/urdf/already/");
insert("6".repeat(12), BASE + "/vibemake" + COVER, "vibemake" + MAIN, "vibemake" + PREFIX);
insert("7".repeat(12), null, ROOT + "/urdf/wrong/a.urdf", ROOT + PREFIX);
insert("8".repeat(12), BASE + ".evil/" + ROOT + COVER, "", "");
insert("9".repeat(12), BASE + "/VIBEMAKE_DEV" + COVER, "", "");
Map<String, Object> externalBefore = row("2".repeat(12));
String publicCover = paths.coverUrl(row(CODE).get("COVER_URL").toString());
String publicMain = paths.publicUrl(ROOT + MAIN);
execute("migration-prepare");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM resource_path_changes", Integer.class)).isEqualTo(1);
execute("migration-apply");
assertThat(row(CODE)).containsEntry("COVER_URL", COVER)
.containsEntry("URDF_MAIN_OBJECT_KEY", MAIN).containsEntry("URDF_PREFIX", PREFIX);
assertThat(paths.coverUrl(row(CODE).get("COVER_URL").toString())).isEqualTo(publicCover);
assertThat(paths.publicUrl(row(CODE).get("URDF_MAIN_OBJECT_KEY").toString())).isEqualTo(publicMain);
assertThat(row("2".repeat(12))).isEqualTo(externalBefore);
assertThat(row("3".repeat(12)).get("COVER_URL")).asString().endsWith("?version=2");
assertThat(row("4".repeat(12)).get("COVER_URL")).asString().endsWith("#preview");
assertThat(row("6".repeat(12)).get("URDF_PREFIX")).isEqualTo("vibemake" + PREFIX);
assertThat(row("7".repeat(12)).get("URDF_PREFIX")).isEqualTo(ROOT + PREFIX);
assertThat(row("8".repeat(12)).get("COVER_URL")).asString().contains(".evil/");
assertThat(row("9".repeat(12)).get("COVER_URL")).asString().contains("/VIBEMAKE_DEV/");
execute("migration-prepare");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM resource_path_changes", Integer.class)).isZero();
execute("migration-apply");
assertThat(row(CODE).get("COVER_URL")).isEqualTo(COVER);
}
@Test
void concurrentChangesAreNotOverwrittenAndNewPathsCanBeRolledBack() {
insert(CODE, BASE + "/" + ROOT + COVER, ROOT + MAIN, ROOT + PREFIX);
execute("migration-prepare");
jdbc.update("UPDATE project SET cover_url = ? WHERE project_code = ?", "https://external.example.com/new.png", CODE);
execute("migration-apply");
assertThat(row(CODE)).containsEntry("COVER_URL", "https://external.example.com/new.png")
.containsEntry("URDF_MAIN_OBJECT_KEY", ROOT + MAIN);
jdbc.update("UPDATE project SET cover_url = ? WHERE project_code = ?", BASE + "/" + ROOT + COVER, CODE);
execute("migration-prepare");
execute("migration-apply");
execute("rollback-prepare");
jdbc.update("INSERT INTO resource_cover_rollback VALUES (?, ?, ?)", CODE, COVER, paths.coverUrl(COVER));
execute("rollback-apply");
assertThat(row(CODE)).containsEntry("COVER_URL", BASE + "/" + ROOT + COVER)
.containsEntry("URDF_MAIN_OBJECT_KEY", ROOT + MAIN).containsEntry("URDF_PREFIX", ROOT + PREFIX);
execute("rollback-apply");
assertThat(row(CODE).get("URDF_PREFIX")).isEqualTo(ROOT + PREFIX);
}
private void insert(String code, String cover, String main, String prefix) {
jdbc.update("INSERT INTO project VALUES (?, ?, ?, ?)", code, cover, main, prefix);
}
@Test
void urdfResumeCommitsEarlierCoverChangeWithoutStartingAnotherTransaction() throws Exception {
insert(CODE, BASE + "/" + ROOT + COVER, ROOT + MAIN, ROOT + PREFIX);
source.getConnection().setAutoCommit(false);
jdbc.update("UPDATE project SET cover_url = ? WHERE project_code = ?", COVER, CODE);
execute("migration-resume-urdf");
JdbcTemplate observer = new JdbcTemplate(
new DriverManagerDataSource("jdbc:h2:mem:migration;MODE=MySQL", "sa", ""));
assertThat(observer.queryForMap("SELECT * FROM project WHERE project_code = ?", CODE))
.containsEntry("COVER_URL", COVER).containsEntry("URDF_MAIN_OBJECT_KEY", MAIN)
.containsEntry("URDF_PREFIX", PREFIX);
execute("migration-resume-urdf");
assertThat(row(CODE).get("URDF_PREFIX")).isEqualTo(PREFIX);
}
private Map<String, Object> row(String code) {
return jdbc.queryForMap("SELECT * FROM project WHERE project_code = ?", code);
}
private void execute(String name) {
Matcher block = Pattern.compile("```sql\\s*-- resource-path-" + name + "\\s+([\\s\\S]*?)```").matcher(document);
assertThat(block.find()).as("文档 SQL 块 %s", name).isTrue();
String sql = block.group(1).replaceAll("(?m)^--.*$", "")
.replace(" COLLATE utf8mb4_bin", "")
.replace(" CHARACTER SET utf8mb4", "")
.replace("DROP TEMPORARY TABLE", "DROP TABLE")
.replace("START TRANSACTION", "SET AUTOCOMMIT FALSE")
.replace("SET NAMES utf8mb4", "")
.replace("<=>", "IS NOT DISTINCT FROM")
.replace("[[:cntrl:]:]", "[\\p{Cntrl}:]");
for (String statement : sql.split(";")) {
if (statement.isBlank()) continue;
Matcher update = Pattern.compile("UPDATE project p JOIN (\\w+) c ON c.project_code = p.project_code\\s+SET ([\\s\\S]*?)\\s+WHERE ([\\s\\S]*)")
.matcher(statement.trim());
if (update.matches()) {
statement = "MERGE INTO project p USING " + update.group(1)
+ " c ON c.project_code = p.project_code WHEN MATCHED AND " + update.group(3)
+ " THEN UPDATE SET " + update.group(2).replace("p.", "");
}
jdbc.execute(statement);
}
}
}
@@ -0,0 +1,36 @@
package com.linkerbot.vibemake.api;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.*;
final class SchemaSupport {
static void reset(JdbcTemplate jdbc) throws IOException {
Path path = Path.of("../docs/database.md");
if (!Files.exists(path)) path = Path.of("docs/database.md");
String content =
Files.readString(path)
+ "\n"
+ Files.readString(path.resolveSibling("admin-database.md"));
Matcher matcher = Pattern.compile("CREATE TABLE [\\s\\S]*?;").matcher(content);
jdbc.execute("DROP ALL OBJECTS");
int tables = 0;
while (matcher.find()) {
String ddl =
matcher.group()
// H2 的 JSON 字符串绑定与 MySQL 不同,测试以文本列承接服务层 JSON。
.replace(
"JSON NOT NULL DEFAULT (JSON_ARRAY())",
"CLOB NOT NULL DEFAULT '[]'")
.replace(" CHARACTER SET utf8mb4 COLLATE utf8mb4_bin", "")
.replaceAll(" COMMENT '[^']*'", "")
.replaceAll("\\) ENGINE=InnoDB[^;]*;", ");");
jdbc.execute(ddl);
tables++;
}
if (tables != 5) throw new IllegalStateException("必须包含四张基础表和迁移任务表");
}
}
File diff suppressed because it is too large Load Diff