package com.custom.webui.controller;
|
|
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
import com.custom.webui.config.props.RagProperties;
|
import com.custom.webui.dto.req.RagBindCategoryRequest;
|
import com.custom.webui.dto.req.RagBindRequest;
|
import com.custom.webui.dto.req.RagSearchRequest;
|
import com.custom.webui.dto.resp.RagChunk;
|
import com.custom.webui.dto.resp.Result;
|
import com.custom.webui.entity.ChatCollection;
|
import com.custom.webui.entity.RagCollection;
|
import com.custom.webui.exception.BusinessException;
|
import com.custom.webui.entity.ChatCategory;
|
import com.custom.webui.mapper.ChatCategoryMapper;
|
import com.custom.webui.mapper.ChatCollectionMapper;
|
import com.custom.webui.mapper.RagCollectionMapper;
|
import com.custom.webui.security.CurrentUser;
|
import com.custom.webui.service.CategoryService;
|
import com.custom.webui.service.ChatService;
|
import com.custom.webui.service.FileService;
|
import com.custom.webui.service.RagProxyService;
|
import jakarta.validation.Valid;
|
import lombok.RequiredArgsConstructor;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RestController;
|
|
import java.time.LocalDateTime;
|
import java.util.ArrayList;
|
import java.util.HashMap;
|
import java.util.List;
|
import java.util.Map;
|
|
/**
|
* RAG 代理接口:把浏览器的 RAG 请求转发给 Python 微服务。
|
*
|
* <p><b>为什么不让前端直连 Python 服务</b>:
|
* <ul>
|
* <li>Python 服务无需实现 JWT 校验,代码更简单(它只信任来自后端的调用)</li>
|
* <li>Python 服务可以只监听内网 / 127.0.0.1,不暴露给浏览器</li>
|
* <li>鉴权、限流、缓存、降级都集中在这一层,便于统一治理</li>
|
* </ul>
|
*/
|
@Slf4j
|
@RestController
|
@RequestMapping("/api/rag")
|
@RequiredArgsConstructor
|
public class RagProxyController {
|
|
private final RagProxyService ragProxyService;
|
private final RagCollectionMapper ragCollectionMapper;
|
private final ChatCollectionMapper chatCollectionMapper;
|
private final ChatService chatService;
|
private final RagProperties ragProperties;
|
private final FileService fileService;
|
private final CategoryService categoryService;
|
private final ChatCategoryMapper chatCategoryMapper;
|
|
/**
|
* 向量检索。
|
*
|
* <p>权限校验:只允许检索属于当前用户的集合。
|
* 若不校验,攻击者可以传入任意集合名读取他人知识库内容 ——
|
* 这是 RAG 系统最典型的越权漏洞。
|
*/
|
@PostMapping("/search")
|
public Result<List<RagChunk>> search(@Valid @RequestBody RagSearchRequest request) {
|
Long userId = CurrentUser.requireUserId();
|
|
List<String> allowed = accessibleCollections(userId);
|
|
List<String> target;
|
if (request.getCollectionNames() != null && !request.getCollectionNames().isEmpty()) {
|
// 指定了集合:与可访问范围求交集,越权的静默剔除
|
target = request.getCollectionNames().stream().filter(allowed::contains).toList();
|
} else if (request.getChatId() != null) {
|
// 未指定集合但给了会话 id:用该会话自己绑定的知识库(含整类展开)。
|
// 比退化成「用户全部知识库」更符合直觉 —— 用户绑了什么就只检索什么。
|
target = collectionsBoundToChat(request.getChatId(), userId).stream()
|
.filter(allowed::contains).toList();
|
} else {
|
target = allowed;
|
}
|
|
if (target.isEmpty()) {
|
// 没有可用知识库时不算错误,返回空结果即可,前端提示「未命中」更友好
|
log.debug("用户 {} 在会话 {} 上没有可检索的集合", userId, request.getChatId());
|
return Result.success(List.of());
|
}
|
|
log.debug("RAG 检索范围: 会话={} 集合数={} 来源={}", request.getChatId(), target.size(),
|
request.getCollectionNames() != null && !request.getCollectionNames().isEmpty()
|
? "请求指定" : request.getChatId() != null ? "会话绑定" : "用户全部");
|
|
int topK = request.getTopK() != null ? request.getTopK() : ragProperties.getDefaultTopK();
|
return Result.success(ragProxyService.search(request.getQuery(), target, topK));
|
}
|
|
/** 把知识库集合绑定到会话,聊天时才会参与检索 */
|
@PostMapping("/bind")
|
@Transactional(rollbackFor = Exception.class)
|
public Result<List<String>> bind(@Valid @RequestBody RagBindRequest request) {
|
Long userId = CurrentUser.requireUserId();
|
chatService.requireOwnedChat(userId, request.getChatId());
|
|
List<String> allowed = accessibleCollections(userId);
|
|
// 只保留当前确实可访问的集合,其余**静默剔除**并记日志。
|
//
|
// 早期实现是对不可访问的集合直接抛 403,但那样会造成一个无法自行
|
// 恢复的死结:绑定是全量覆盖语义,前端的 boundCollections 里只要
|
// 残留一个已失效的集合名(文档被删了、被管理员取消了全局标记等),
|
// 之后每一次绑定都会把它一并提交 → 每次都 403 → 而这条坏绑定
|
// 永远不会被清掉。用户看到的是「无权选择知识库集合」,
|
// 但真实原因与权限无关,纯粹是引用了已不存在的集合,极难自行排查。
|
//
|
// 改为「过滤 + 告知」:真正越权的集合不会生效(安全边界不变),
|
// 同时返回实际绑定的列表,让前端得以自我修复。
|
List<String> accepted = new ArrayList<>();
|
List<String> rejected = new ArrayList<>();
|
for (String collection : request.getCollectionNames()) {
|
if (collection == null || collection.isBlank()) {
|
continue;
|
}
|
if (allowed.contains(collection)) {
|
if (!accepted.contains(collection)) {
|
accepted.add(collection);
|
}
|
} else {
|
rejected.add(collection);
|
}
|
}
|
if (!rejected.isEmpty()) {
|
log.warn("会话 {} 绑定请求中有 {} 个集合不可访问,已忽略: {}(通常是文档被删除,"
|
+ "或管理员取消了全局标记;这不是权限错误)",
|
request.getChatId(), rejected.size(), rejected);
|
}
|
|
// 全量覆盖语义:accepted 就是该会话最终要挂载的集合列表
|
chatCollectionMapper.delete(
|
Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, request.getChatId()));
|
for (String collection : accepted) {
|
ChatCollection entity = new ChatCollection();
|
entity.setChatId(request.getChatId());
|
entity.setCollectionName(collection);
|
entity.setCreatedAt(LocalDateTime.now());
|
chatCollectionMapper.insert(entity);
|
}
|
|
log.info("会话 {} 绑定知识库 {} 个: {}(忽略 {} 个)", request.getChatId(),
|
accepted.size(), accepted, rejected.size());
|
return Result.success(accepted);
|
}
|
|
/** 查询会话已绑定的知识库集合 */
|
@GetMapping("/bind/{chatId}")
|
public Result<List<String>> listBindings(@PathVariable Long chatId) {
|
chatService.requireOwnedChat(CurrentUser.requireUserId(), chatId);
|
List<String> collections = chatCollectionMapper.selectList(
|
Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId))
|
.stream().map(ChatCollection::getCollectionName).toList();
|
return Result.success(collections);
|
}
|
|
/**
|
* 整类绑定:把一个知识库分类挂到会话上。
|
*
|
* <p>与 {@code /bind} 的区别:这里存的是**分类 id**,检索时才展开成集合。
|
* 好处是之后往分类里新增文档,已有会话自动能检索到 ——
|
* 若在绑定时就把集合名写死,新文档永远进不了这个会话。
|
*
|
* @param bind true 绑定,false 解绑
|
*/
|
@PostMapping("/bind-category")
|
@Transactional(rollbackFor = Exception.class)
|
public Result<List<Long>> bindCategory(@Valid @RequestBody RagBindCategoryRequest request) {
|
Long userId = CurrentUser.requireUserId();
|
chatService.requireOwnedChat(userId, request.getChatId());
|
|
// 可见性校验放在 CategoryService 里(自己的 + 全局的),
|
// 越权分类会被拒绝
|
if (Boolean.TRUE.equals(request.getBind())) {
|
categoryService.requireVisibleForUser(userId, request.getCategoryId());
|
Long exists = chatCategoryMapper.selectCount(
|
Wrappers.<ChatCategory>lambdaQuery()
|
.eq(ChatCategory::getChatId, request.getChatId())
|
.eq(ChatCategory::getCategoryId, request.getCategoryId()));
|
if (exists == null || exists == 0) {
|
ChatCategory entity = new ChatCategory();
|
entity.setChatId(request.getChatId());
|
entity.setCategoryId(request.getCategoryId());
|
entity.setCreatedAt(LocalDateTime.now());
|
chatCategoryMapper.insert(entity);
|
}
|
} else {
|
chatCategoryMapper.delete(
|
Wrappers.<ChatCategory>lambdaQuery()
|
.eq(ChatCategory::getChatId, request.getChatId())
|
.eq(ChatCategory::getCategoryId, request.getCategoryId()));
|
}
|
|
List<Long> bound = chatCategoryMapper.selectList(
|
Wrappers.<ChatCategory>lambdaQuery().eq(ChatCategory::getChatId, request.getChatId()))
|
.stream().map(ChatCategory::getCategoryId).toList();
|
log.info("会话 {} {} 分类 {},当前绑定分类: {}",
|
request.getChatId(), Boolean.TRUE.equals(request.getBind()) ? "绑定" : "解绑",
|
request.getCategoryId(), bound);
|
return Result.success(bound);
|
}
|
|
/** 查询会话已绑定的分类 id 列表 */
|
@GetMapping("/bind-category/{chatId}")
|
public Result<List<Long>> listCategoryBindings(@PathVariable Long chatId) {
|
chatService.requireOwnedChat(CurrentUser.requireUserId(), chatId);
|
return Result.success(chatCategoryMapper.selectList(
|
Wrappers.<ChatCategory>lambdaQuery().eq(ChatCategory::getChatId, chatId))
|
.stream().map(ChatCategory::getCategoryId).toList());
|
}
|
|
/** 解除会话的全部知识库绑定(含整类绑定) */
|
@DeleteMapping("/bind/{chatId}")
|
public Result<Void> unbind(@PathVariable Long chatId) {
|
chatService.requireOwnedChat(CurrentUser.requireUserId(), chatId);
|
chatCollectionMapper.delete(
|
Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId));
|
chatCategoryMapper.delete(
|
Wrappers.<ChatCategory>lambdaQuery().eq(ChatCategory::getChatId, chatId));
|
return Result.success();
|
}
|
|
/**
|
* RAG 服务健康状态,供前端在设置页展示「知识库服务:正常/不可用」。
|
*/
|
@GetMapping("/health")
|
public Result<Map<String, Object>> health() {
|
Map<String, Object> status = new HashMap<>();
|
status.put("enabled", ragProperties.isEnabled());
|
status.put("baseUrl", ragProperties.getBaseUrl());
|
status.put("available", ragProxyService.isHealthy());
|
status.put("ownedCollections", accessibleCollections(CurrentUser.requireUserId()));
|
return Result.success(status);
|
}
|
|
/**
|
* 取某会话已绑定的集合:单篇绑定 ∪ 整类绑定展开。
|
*
|
* <p>与 {@code MessageServiceImpl.buildContext()} 里的展开逻辑保持一致 ——
|
* 那边是聊天主链路,这里是检索接口,两处必须用同一套规则,
|
* 否则会出现「聊天能检索到、手动检索检索不到」这种诡异现象。
|
*/
|
private List<String> collectionsBoundToChat(Long chatId, Long userId) {
|
chatService.requireOwnedChat(userId, chatId);
|
|
List<String> result = new ArrayList<>(chatCollectionMapper.selectList(
|
Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId))
|
.stream().map(ChatCollection::getCollectionName).toList());
|
|
List<Long> categoryIds = chatCategoryMapper.selectList(
|
Wrappers.<ChatCategory>lambdaQuery().eq(ChatCategory::getChatId, chatId))
|
.stream().map(ChatCategory::getCategoryId).toList();
|
if (!categoryIds.isEmpty()) {
|
for (Long categoryId : categoryIds) {
|
for (String name : categoryService.collectionsOfCategory(userId, categoryId)) {
|
if (!result.contains(name)) {
|
result.add(name);
|
}
|
}
|
}
|
}
|
return result;
|
}
|
|
/**
|
* 当前用户**可检索**的全部集合名 = 自己入库的 + 全部已入库的全局知识库。
|
*
|
* <p>这是知识库权限的唯一判定入口:检索、绑定、健康检查都走它,
|
* 保证「全局文件人人可用、私有文件互不可见」。
|
* 具体实现放在 FileService,避免权限逻辑散落在多个 Controller 里。
|
*/
|
private List<String> accessibleCollections(Long userId) {
|
return fileService.accessibleCollections(userId);
|
}
|
}
|