This commit is contained in:
lxp
2026-10-14 16:55:07 +08:00
parent fb1a31f782
commit 92b2251f25
29 changed files with 1769 additions and 12 deletions
@@ -17,7 +17,8 @@ public class OpenApiConfiguration {
.version("v1")
.description(
"四表社区后端。登录仅邮箱和图片验证码,无法验证邮箱归属。Gitea"
+ " 仓库统一存放在组织下。文件下载返回二进制,其余响应使用统一包装。"))
+ " 仓库统一存放在组织下。文件下载返回二进制,AI 对话返回 SSE,"
+ "其余响应及 SSE 事件数据使用统一包装。"))
.components(
new Components()
.addSecuritySchemes(
@@ -0,0 +1,30 @@
package com.linkerbot.community.api.controller;
import com.linkerbot.community.bean.ai.AiContracts.ChatRequest;
import com.linkerbot.community.security.CurrentUser;
import com.linkerbot.community.service.AiSearchService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/community/ai")
@Tag(name = "AI 项目搜索")
public class AiSearchController {
private final AiSearchService searches;
@PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@Operation(summary = "通过连续对话检索已发布社区项目,返回 SSE 进度和结果")
public SseEmitter chat(@Valid @RequestBody ChatRequest request, HttpServletResponse response) {
SseEmitter emitter = searches.chat(CurrentUser.required(), request);
response.setHeader("Cache-Control", "no-cache, no-store");
response.setHeader("X-Accel-Buffering", "no");
return emitter;
}
}
@@ -1,6 +1,6 @@
spring:
datasource:
url: ${DB_URL:jdbc:mysql://localhost:3306/community?useUnicode=true&characterEncoding=utf8&connectionTimeZone=UTC}
url: ${DB_URL:jdbc:mysql://localhost:3306/community?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai}
username: ${DB_USERNAME:root}
password: ${DB_PASSWORD:}
driver-class-name: com.mysql.cj.jdbc.Driver
@@ -20,6 +20,16 @@ mybatis-plus:
configuration:
map-underscore-to-camel-case: true
community:
ai:
enabled: ${AI_ENABLED:true}
api-key: ${ARK_API_KEY:}
model: ${ARK_MODEL:doubao-seed-2-1-lite-260915}
endpoint: ${ARK_ENDPOINT:https://ark.cn-beijing.volces.com/api/v3/responses}
request-timeout: ${AI_REQUEST_TIMEOUT:30s}
search-timeout: ${AI_SEARCH_TIMEOUT:65s}
heartbeat-interval: 10s
max-concurrent: ${AI_MAX_CONCURRENT:4}
requests-per-minute: ${AI_REQUESTS_PER_MINUTE:10}
types:
GENERAL: 通用
HUMANOID: 人形
@@ -0,0 +1,98 @@
package com.linkerbot.community.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.community.bean.entity.Project;
import com.linkerbot.community.bean.entity.User;
import com.linkerbot.community.common.Codes;
import com.linkerbot.community.security.TokenService;
import com.linkerbot.community.service.UserService;
import com.linkerbot.community.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.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 = "COMMUNITY_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", "community.ai.enabled=true",
"logging.level.root=INFO", "logging.level.com.linkerbot.community=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 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()));
JsonNode second = chat(token, Map.of("message", "改成轮式,其他要求不变。",
"history", List.of(Map.of("role", "user", "content", question),
Map.of("role", "assistant", "content", first.path("reply").asText())),
"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));
}
}
@@ -0,0 +1,398 @@
package com.linkerbot.community.api;
import static org.assertj.core.api.Assertions.*;
import static org.awaitility.Awaitility.await;
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.fasterxml.jackson.databind.node.ObjectNode;
import com.linkerbot.community.bean.entity.Project;
import com.linkerbot.community.bean.entity.User;
import com.linkerbot.community.common.BusinessException;
import com.linkerbot.community.common.Codes;
import com.linkerbot.community.security.TokenService;
import com.linkerbot.community.service.ai.AiModelClient;
import com.linkerbot.community.service.config.AiProperties;
import com.linkerbot.community.service.mapper.ProjectMapper;
import com.linkerbot.community.service.mapper.UserMapper;
import jakarta.servlet.AsyncEvent;
import jakarta.servlet.AsyncListener;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.*;
import org.springframework.boot.test.context.*;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mock.web.MockAsyncContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.*;
@SpringBootTest(properties = {
"spring.datasource.url=jdbc:h2:mem:ai;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.username=sa", "spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"community.ai.enabled=true", "community.ai.api-key=local-test-placeholder",
"community.ai.max-concurrent=2", "community.ai.search-timeout=4s",
"community.ai.heartbeat-interval=100ms", "logging.level.org.springframework=WARN",
"logging.level.root=INFO", "debug=false"
})
@ActiveProfiles("test")
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
@Import(AiSearchTest.Config.class)
class AiSearchTest {
@TestConfiguration
static class Config {
@Bean @Primary FakeModel fakeModel() { return new FakeModel(); }
}
static class FakeModel implements AiModelClient {
volatile BiFunction<String, JsonNode, JsonNode> handler;
final List<JsonNode> inputs = new CopyOnWriteArrayList<>();
@Override public JsonNode complete(String name, JsonNode schema, String prompt, JsonNode input) {
inputs.add(input.deepCopy());
return handler.apply(name, input);
}
}
private static final AtomicLong USER_SEQUENCE = new AtomicLong(1000);
@Autowired MockMvc mvc;
@Autowired ObjectMapper json;
@Autowired JdbcTemplate jdbc;
@Autowired ProjectMapper projects;
@Autowired UserMapper users;
@Autowired TokenService tokens;
@Autowired AiProperties properties;
@Autowired FakeModel model;
private User user;
private String token;
@BeforeEach void reset() throws Exception {
SchemaSupport.reset(jdbc);
user = new User();
user.setId(USER_SEQUENCE.incrementAndGet());
user.setUserCode(Codes.next());
user.setEmail("ai@example.invalid");
user.setNickname("测试用户");
user.setStatus("ACTIVE");
user.setCreatedAt(LocalDateTime.now());
user.setUpdatedAt(user.getCreatedAt());
users.insert(user);
token = tokens.issue(user.getId());
properties.setEnabled(true);
properties.setRequestsPerMinute(10);
properties.setSearchTimeout(Duration.ofSeconds(4));
model.inputs.clear();
model.handler = (name, input) -> name.endsWith("intent") ? intent(null, List.of()) : rank(input);
}
private Project project(String name, String type, String description) {
Project project = new Project();
project.setProjectCode(Codes.next());
project.setOwnerUserId(user.getId());
project.setName(name);
project.setDescription(description);
project.setProjectType(type);
project.setGiteaOwner("community");
project.setGiteaRepoName("p_" + project.getProjectCode());
project.setRepoStatus("READY");
project.setPublishStatus("PUBLISHED");
project.setPublishedCommitSha("a".repeat(40));
project.setPublishedAt(LocalDateTime.now());
project.setCreatedAt(project.getPublishedAt());
project.setUpdatedAt(project.getPublishedAt());
project.setDeleted(false);
projects.insert(project);
return project;
}
private ObjectNode intent(String type, List<String> keywords) {
ObjectNode node = json.createObjectNode().put("projectType", type).put("clarification", "");
node.set("keywords", json.valueToTree(keywords));
node.putArray("requirements"); node.putArray("preferences"); node.putArray("focusProjectCodes");
return node;
}
private ObjectNode rank(JsonNode input) {
JsonNode first = input.path("candidates").get(0);
return selection(first.path("projectCode").asText(), "name", first.path("name").asText());
}
private ObjectNode selection(String code, String field, String quote) {
ObjectNode node = json.createObjectNode();
ObjectNode card = node.putArray("selections").addObject().put("projectCode", code).put("reason", "项目资料包含相应信息。");
card.putArray("evidence").addObject().put("field", field).put("quote", quote)
.putNull("requirementIndex").putNull("preferenceIndex");
return node;
}
private MvcResult start(Object body) throws Exception {
return 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();
}
private List<JsonNode> finish(MvcResult initial) throws Exception {
initial.getAsyncResult(6000);
MvcResult result = mvc.perform(asyncDispatch(initial)).andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith("text/event-stream")).andReturn();
String requestId = initial.getResponse().getHeader("X-Request-Id");
String body = result.getResponse().getContentAsString(StandardCharsets.UTF_8);
List<JsonNode> events = new ArrayList<>();
for (String line : body.split("\\R")) {
if (!line.startsWith("data:")) continue;
JsonNode event = json.readTree(line.substring(5));
assertThat(event.path("requestId").asText()).isEqualTo(requestId);
events.add(event);
}
assertThat(events).isNotEmpty();
return events;
}
private JsonNode chat() throws Exception {
List<JsonNode> events = finish(start(Map.of("message", "推荐机器人项目")));
return events.getLast();
}
@ParameterizedTest
@ValueSource(strings = {"GENERAL", "HUMANOID", "QUADRUPED", "WHEELED"})
void filtersConfiguredTypesAndKeepsProjectContract(String type) throws Exception {
Project expected = project("教学机器人", type, "支持 ROS2 教学");
project("其他机器人", "OTHER", "ROS2");
model.handler = (name, input) -> name.endsWith("intent") ? intent(type, List.of("ROS2", "ROS 2")) : rank(input);
MvcResult initial = start(Map.of("message", "找教学项目"));
List<JsonNode> events = finish(initial);
assertThat(events.stream().filter(event -> event.path("data").has("stage"))
.map(event -> event.path("data").path("stage").asText()).toList())
.containsExactly("understanding", "searching", "ranking", "validating");
JsonNode card = events.getLast().path("data").path("projects").get(0);
assertThat(card.path("project").path("projectCode").asText()).isEqualTo(expected.getProjectCode());
assertThat(card.path("project").path("owner").has("id")).isFalse();
assertThat(card.path("project").has("id")).isFalse();
assertThat(card.path("project").has("giteaRepoId")).isFalse();
assertThat(card.path("project").has("likeCount")).isTrue();
}
@Test void noTypeSearchesAllTypesAndNameOutranksDescription() throws Exception {
Project expected = project("ROS2 示例", "HUMANOID", "教学");
project("新项目", "WHEELED", "ROS2 教学");
model.handler = (name, input) -> name.endsWith("intent") ? intent(null, List.of("ROS2")) : rank(input);
assertThat(chat().path("data").path("projects").get(0).path("project").path("projectCode").asText())
.isEqualTo(expected.getProjectCode());
}
@Test void preservesHistoryAndOriginalPositionsForFollowup() throws Exception {
Project hidden = project("第一个", "GENERAL", "已撤下");
hidden.setPublishStatus("UNPUBLISHED"); projects.updateById(hidden);
Project second = project("轮式教学", "WHEELED", "使用 ROS2");
model.handler = (name, input) -> {
if (!name.endsWith("intent")) return rank(input);
assertThat(input.path("history").size()).isEqualTo(2);
assertThat(input.path("previousProjects").size()).isEqualTo(1);
assertThat(input.path("previousProjects").get(0).path("position").asInt()).isEqualTo(2);
ObjectNode intent = intent("WHEELED", List.of());
intent.withArray("focusProjectCodes").add(second.getProjectCode());
return intent;
};
List<JsonNode> result = finish(start(Map.of("message", "第二个项目支持什么", "history", List.of(
Map.of("role", "user", "content", "找四足教学项目"),
Map.of("role", "assistant", "content", "以下是项目")),
"previousProjectCodes", List.of(hidden.getProjectCode(), second.getProjectCode()))));
assertThat(result.getLast().path("data").path("status").asText()).isEqualTo("MATCHED");
}
@Test void hiddenProjectsNeverReachModelAndEmptyCandidatesSkipRanking() throws Exception {
Project unpublished = project("未发布", "GENERAL", "ROS2");
unpublished.setPublishStatus("UNPUBLISHED"); projects.updateById(unpublished);
Project deleted = project("删除", "GENERAL", "ROS2");
deleted.setDeleted(true); projects.updateById(deleted);
Project creating = project("初始化", "GENERAL", "ROS2");
creating.setRepoStatus("CREATING"); projects.updateById(creating);
assertThat(chat().path("data").path("status").asText()).isEqualTo("NO_MATCH");
assertThat(model.inputs).hasSize(1);
}
@Test void noMatchAndClarificationAreBusinessResults() throws Exception {
model.handler = (name, input) -> intent(null, List.of()).put("clarification", "你希望找到什么用途的项目?");
assertThat(chat().path("data").path("status").asText()).isEqualTo("NEEDS_CLARIFICATION");
assertThat(model.inputs).hasSize(1);
}
@Test void capsCandidatesAndEscapesLikeWildcards() throws Exception {
for (int index = 0; index < 22; index++) project("项目" + index, "GENERAL", "教学");
chat();
assertThat(model.inputs.getLast().path("candidates").size()).isEqualTo(20);
project("100%_教学", "GENERAL", "特殊字符");
model.handler = (name, input) -> name.endsWith("intent") ? intent(null, List.of("%_")) : rank(input);
chat();
assertThat(model.inputs.getLast().path("candidates").size()).isEqualTo(1);
}
@Test void rejectsForgedCodeAndFabricatedEvidenceAndMalformedShape() throws Exception {
Project project = project("教学", "QUADRUPED", "ROS2");
for (String scenario : List.of("code", "quote", "shape", "focus")) {
model.handler = (name, input) -> {
if (name.endsWith("intent")) {
ObjectNode intent = intent(null, List.of());
if (scenario.equals("focus")) intent.withArray("focusProjectCodes").add(Codes.next());
return intent;
}
if (scenario.equals("shape")) return json.createObjectNode();
return selection(scenario.equals("code") ? Codes.next() : project.getProjectCode(),
"description", scenario.equals("quote") ? "载重100公斤" : "ROS2");
};
assertThat(chat().path("code").asText()).isEqualTo("AI_INVALID_RESPONSE");
}
}
@Test void requiresProofForHardRequirementsAndMarksUnknownPreferences() throws Exception {
Project project = project("教学", "QUADRUPED", "支持 ROS2");
model.handler = (name, input) -> {
if (name.endsWith("intent")) {
ObjectNode intent = intent("QUADRUPED", List.of("ROS2"));
intent.withArray("requirements").add("支持 ROS2");
intent.withArray("preferences").add("适合室外");
return intent;
}
ObjectNode response = selection(project.getProjectCode(), "description", "支持 ROS2");
((ObjectNode) response.path("selections").get(0).path("evidence").get(0)).put("requirementIndex", 0);
return response;
};
assertThat(chat().path("data").path("projects").get(0).path("unverifiedRequirements").get(0).asText())
.isEqualTo("适合室外");
model.handler = (name, input) -> {
if (!name.endsWith("intent")) return selection(project.getProjectCode(), "description", "支持 ROS2");
ObjectNode intent = intent(null, List.of()); intent.withArray("requirements").add("支持 ROS2"); return intent;
};
assertThat(chat().path("code").asText()).isEqualTo("AI_INVALID_RESPONSE");
}
@Test void rechecksWithdrawalAndMetadataChangesAfterRanking() throws Exception {
for (String change : List.of("withdraw", "description", "sha")) {
jdbc.update("DELETE FROM project");
Project project = project("教学", "GENERAL", "ROS2");
model.handler = (name, input) -> {
if (name.endsWith("intent")) return intent(null, List.of());
if (change.equals("withdraw")) project.setPublishStatus("UNPUBLISHED");
else if (change.equals("description")) project.setDescription("内容已修改");
else project.setPublishedCommitSha("b".repeat(40));
projects.updateById(project);
return rank(input);
};
assertThat(chat().path("data").path("status").asText()).isEqualTo("NO_MATCH");
}
}
@Test void oneQuoteCanSupportBothRequirementAndPreference() throws Exception {
Project project = project("教学", "QUADRUPED", "支持 ROS2 教学");
model.handler = (name, input) -> {
if (name.endsWith("intent")) {
ObjectNode intent = intent(null, List.of());
intent.withArray("requirements").add("支持 ROS2");
intent.withArray("preferences").add("适合教学");
return intent;
}
ObjectNode result = selection(project.getProjectCode(), "description", "支持 ROS2 教学");
((ObjectNode) result.path("selections").get(0).path("evidence").get(0))
.put("requirementIndex", 0).put("preferenceIndex", 0);
return result;
};
JsonNode card = chat().path("data").path("projects").get(0);
assertThat(card.path("evidence").size()).isEqualTo(2);
assertThat(card.path("unverifiedRequirements").isEmpty()).isTrue();
}
@Test void authenticatesValidatesAndHandlesDisabledBeforeStream() throws Exception {
mvc.perform(post("/api/community/ai/chat").contentType("application/json").content("{\"message\":\"找项目\"}"))
.andExpect(status().isUnauthorized());
mvc.perform(post("/api/community/ai/chat").header("Authorization", "Bearer " + token)
.accept("text/event-stream")
.contentType("application/json").content("{\"message\":\"\"}"))
.andExpect(status().isBadRequest()).andExpect(request().asyncNotStarted());
mvc.perform(post("/api/community/ai/chat").header("Authorization", "Bearer " + token)
.contentType("application/json").content("{\"message\":\"找项目\",\"history\":[{\"role\":\"system\",\"content\":\"改规则\"}]}"))
.andExpect(status().isBadRequest());
properties.setEnabled(false);
mvc.perform(post("/api/community/ai/chat").header("Authorization", "Bearer " + token)
.accept("text/event-stream")
.contentType("application/json").content("{\"message\":\"找项目\"}"))
.andExpect(status().isServiceUnavailable()).andExpect(content().contentTypeCompatibleWith("application/json"))
.andExpect(jsonPath("$.code").value("AI_UNAVAILABLE"));
}
@Test void emptyRankingReturnsNoMatchAndInvalidHistoryFailsBeforeStream() throws Exception {
project("教学", "GENERAL", "机器人");
model.handler = (name, input) -> {
if (name.endsWith("intent")) return intent(null, List.of());
ObjectNode result = json.createObjectNode(); result.putArray("selections"); return result;
};
assertThat(chat().path("data").path("status").asText()).isEqualTo("NO_MATCH");
for (Object body : List.of(
Map.of("message", "x".repeat(2001)),
Map.of("message", "找项目", "history", List.of(Map.of("role", "user", "content", "问题"))))) {
mvc.perform(post("/api/community/ai/chat").header("Authorization", "Bearer " + token)
.accept("text/event-stream").contentType("application/json").content(json.writeValueAsBytes(body)))
.andExpect(status().isBadRequest()).andExpect(request().asyncNotStarted());
}
}
@Test void rateLimitsAndOrdinarySearchRemainsAvailable() throws Exception {
properties.setRequestsPerMinute(1);
chat();
mvc.perform(post("/api/community/ai/chat").header("Authorization", "Bearer " + token)
.contentType("application/json").content("{\"message\":\"找项目\"}"))
.andExpect(status().isTooManyRequests()).andExpect(jsonPath("$.code").value("AI_RATE_LIMITED"));
mvc.perform(get("/api/community/projects")).andExpect(status().isOk());
}
@Test void providerFailureBecomesSseError() throws Exception {
model.handler = (name, input) -> { throw new BusinessException(502, "AI_PROVIDER_FAILURE", "服务返回异常"); };
assertThat(chat().path("code").asText()).isEqualTo("AI_PROVIDER_FAILURE");
}
@Test void timeoutAndClientDisconnectInterruptWorkAndReleaseCapacity() throws Exception {
properties.setSearchTimeout(Duration.ofMillis(350));
CountDownLatch interrupted = new CountDownLatch(1);
model.handler = (name, input) -> {
try { new CountDownLatch(1).await(); }
catch (InterruptedException error) { interrupted.countDown(); Thread.currentThread().interrupt(); }
throw new BusinessException(499, "AI_CANCELLED", "已取消");
};
assertThat(chat().path("code").asText()).isEqualTo("AI_TIMEOUT");
assertThat(interrupted.await(2, TimeUnit.SECONDS)).isTrue();
properties.setSearchTimeout(Duration.ofSeconds(4));
CountDownLatch entered = new CountDownLatch(2);
CountDownLatch cancelled = new CountDownLatch(2);
model.handler = (name, input) -> {
entered.countDown();
try { new CountDownLatch(1).await(); }
catch (InterruptedException error) { cancelled.countDown(); Thread.currentThread().interrupt(); }
throw new BusinessException(499, "AI_CANCELLED", "已取消");
};
MvcResult first = start(Map.of("message", "找项目"));
MvcResult second = start(Map.of("message", "找项目"));
assertThat(entered.await(2, TimeUnit.SECONDS)).isTrue();
mvc.perform(post("/api/community/ai/chat").header("Authorization", "Bearer " + token)
.contentType("application/json").content("{\"message\":\"找项目\"}"))
.andExpect(status().isTooManyRequests()).andExpect(jsonPath("$.code").value("AI_BUSY"));
for (MvcResult active : List.of(first, second)) {
MockAsyncContext context = (MockAsyncContext) active.getRequest().getAsyncContext();
for (AsyncListener listener : context.getListeners()) listener.onError(new AsyncEvent(context, new IOException("closed")));
}
assertThat(cancelled.await(2, TimeUnit.SECONDS)).isTrue();
model.handler = (name, input) -> intent(null, List.of());
await().atMost(Duration.ofSeconds(2)).untilAsserted(() ->
assertThat(chat().path("data").path("status").asText()).isEqualTo("NO_MATCH"));
}
}