package com.custom.webui.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.custom.webui.dto.req.ChatCreateRequest; import com.custom.webui.dto.req.ChatMetaRequest; import com.custom.webui.dto.req.ChatUpdateRequest; import com.custom.webui.dto.resp.ChatDTO; import com.custom.webui.entity.Chat; import com.custom.webui.entity.ChatCollection; import com.custom.webui.entity.Message; import com.custom.webui.entity.UploadFile; import com.custom.webui.exception.BusinessException; import com.custom.webui.mapper.ChatCollectionMapper; import com.custom.webui.mapper.ChatMapper; import com.custom.webui.mapper.MessageMapper; import com.custom.webui.mapper.UploadFileMapper; import com.custom.webui.service.ChatService; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.Set; import java.util.Locale; import java.util.LinkedHashSet; import java.util.LinkedHashMap; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** 会话服务实现。 */ @Slf4j @Service @RequiredArgsConstructor public class ChatServiceImpl implements ChatService { private static final String DEFAULT_TITLE = "新对话"; /** 搜索片段中关键词前后保留的字符数 */ private static final int CONTEXT_LENGTH = 40; /** 无命中位置(理论上不会走到)时的片段长度 */ private static final int SNIPPET_LENGTH = 100; private final ChatMapper chatMapper; private final MessageMapper messageMapper; private final UploadFileMapper uploadFileMapper; private final ChatCollectionMapper chatCollectionMapper; private final ObjectMapper objectMapper; @Override public List listByUser(Long userId) { List chats = chatMapper.selectList( Wrappers.lambdaQuery() .eq(Chat::getUserId, userId) .orderByDesc(Chat::getUpdatedAt)); if (chats.isEmpty()) { return Collections.emptyList(); } // 一次性聚合消息数,避免在循环里对每个会话查一次(N+1 查询) List chatIds = chats.stream().map(Chat::getId).toList(); Map countByChat = messageMapper.selectList( Wrappers.lambdaQuery() .select(Message::getChatId) .in(Message::getChatId, chatIds)) .stream() .collect(Collectors.groupingBy(Message::getChatId, Collectors.counting())); // 同样一次性取出所有会话的知识库绑定 Map> collectionsByChat = chatCollectionMapper.selectList( Wrappers.lambdaQuery().in(ChatCollection::getChatId, chatIds)) .stream() .collect(Collectors.groupingBy(ChatCollection::getChatId, Collectors.mapping(ChatCollection::getCollectionName, Collectors.toList()))); return chats.stream() .map(c -> toDto(c, countByChat.getOrDefault(c.getId(), 0L), collectionsByChat.getOrDefault(c.getId(), Collections.emptyList()))) .toList(); } @Override @Transactional(rollbackFor = Exception.class) public ChatDTO create(Long userId, ChatCreateRequest request) { Chat chat = new Chat(); chat.setUserId(userId); chat.setTitle(request != null && request.getTitle() != null && !request.getTitle().isBlank() ? request.getTitle().trim() : DEFAULT_TITLE); chat.setMeta(writeMeta(request == null ? null : request.getMeta())); chat.setCreatedAt(LocalDateTime.now()); chat.setUpdatedAt(LocalDateTime.now()); chatMapper.insert(chat); log.info("新建会话 userId={} chatId={}", userId, chat.getId()); return toDto(chat, 0L, Collections.emptyList()); } @Override @Transactional(rollbackFor = Exception.class) public ChatDTO update(Long userId, Long chatId, ChatUpdateRequest request) { Chat existing = requireOwnedChat(userId, chatId); Chat update = new Chat(); update.setId(chatId); if (request.getTitle() != null) { String title = request.getTitle().trim(); if (title.isEmpty()) { throw BusinessException.badRequest("标题不能为空"); } // 防御超长标题:列宽 255,超出部分直接截断而不是报数据库错误 update.setTitle(title.length() > 255 ? title.substring(0, 255) : title); } if (request.getMeta() != null) { // meta 是整体覆盖语义:前端应提交完整的参数对象 update.setMeta(writeMeta(request.getMeta())); } update.setUpdatedAt(LocalDateTime.now()); chatMapper.updateById(update); Chat refreshed = chatMapper.selectById(chatId); Long messageCount = messageMapper.selectCount( Wrappers.lambdaQuery().eq(Message::getChatId, chatId)); List collections = chatCollectionMapper.selectList( Wrappers.lambdaQuery().eq(ChatCollection::getChatId, chatId)) .stream().map(ChatCollection::getCollectionName).toList(); log.debug("更新会话 chatId={} 原meta={} 新meta={}", chatId, existing.getMeta(), refreshed.getMeta()); return toDto(refreshed, messageCount, collections); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Long userId, Long chatId) { requireOwnedChat(userId, chatId); // 显式级联:先删子表再删主表,避免留下孤儿数据。 // 不使用数据库外键是刻意选择 —— 便于分库分表和批量导入,代价是要自己保证一致性。 int msgDeleted = messageMapper.delete( Wrappers.lambdaQuery().eq(Message::getChatId, chatId)); chatCollectionMapper.delete( Wrappers.lambdaQuery().eq(ChatCollection::getChatId, chatId)); // 会话绑定的文件解除会话绑定(文件本体与向量集合保留,用户可继续在别处使用) List boundFiles = uploadFileMapper.selectList( Wrappers.lambdaQuery().eq(UploadFile::getChatId, chatId)); for (UploadFile f : boundFiles) { UploadFile patch = new UploadFile(); patch.setId(f.getId()); patch.setChatId(null); uploadFileMapper.updateById(patch); } chatMapper.deleteById(chatId); log.info("删除会话 userId={} chatId={} 连带删除消息 {} 条、解绑文件 {} 个", userId, chatId, msgDeleted, boundFiles.size()); } @Override public Chat requireOwnedChat(Long userId, Long chatId) { if (chatId == null) { throw BusinessException.badRequest("会话 id 不能为空"); } Chat chat = chatMapper.selectById(chatId); // 不存在与不属于当前用户统一返回 404: // 若返回 403 就等于告诉攻击者「这个 id 是存在的」,属于信息泄露。 if (chat == null || !chat.getUserId().equals(userId)) { throw BusinessException.notFound("会话不存在或无权访问"); } return chat; } @Override public ChatMetaRequest parseMeta(Chat chat) { if (chat == null || chat.getMeta() == null || chat.getMeta().isBlank()) { return new ChatMetaRequest(); } try { ChatMetaRequest meta = objectMapper.readValue(chat.getMeta(), ChatMetaRequest.class); return meta == null ? new ChatMetaRequest() : meta; } catch (Exception e) { // 脏数据不应导致整个请求失败,降级为默认参数并留下告警 log.warn("会话 meta 解析失败 chatId={} raw={}", chat.getId(), chat.getMeta()); return new ChatMetaRequest(); } } @Override @Transactional(rollbackFor = Exception.class) public void updateTitle(Long chatId, String title) { if (title == null || title.isBlank()) { return; } String normalized = title.trim(); Chat update = new Chat(); update.setId(chatId); update.setTitle(normalized.length() > 255 ? normalized.substring(0, 255) : normalized); update.setUpdatedAt(LocalDateTime.now()); chatMapper.updateById(update); } @Override public List search(Long userId, String keyword, int limit) { if (keyword == null || keyword.isBlank()) { // 空关键词直接返回空,而不是返回全部会话 —— // 否则搜索框会退化成「无过滤列表」,和侧边栏本身重复 return Collections.emptyList(); } String kw = keyword.trim(); int max = limit > 0 ? Math.min(limit, 100) : 30; // 先取该用户全部会话(个人会话量级通常在数百,一次查完再做内存匹配, // 比两次 LIKE 查询 + 合并更简单,也避免了 title/message 两次往返)。 List chats = chatMapper.selectList( Wrappers.lambdaQuery() .eq(Chat::getUserId, userId) .orderByDesc(Chat::getUpdatedAt)); if (chats.isEmpty()) { return Collections.emptyList(); } Map chatById = new LinkedHashMap<>(); for (Chat c : chats) { chatById.put(c.getId(), c); } // 命中标题的会话 Set titleHits = new LinkedHashSet<>(); String lowerKw = kw.toLowerCase(Locale.ROOT); for (Chat c : chats) { if (c.getTitle() != null && c.getTitle().toLowerCase(Locale.ROOT).contains(lowerKw)) { titleHits.add(c.getId()); } } // 命中消息内容的会话:取每个命中会话的**最早一条**命中消息作为片段。 // 用 Map 去重,避免同一个会话因多条消息命中而重复出现。 Map contentHits = new LinkedHashMap<>(); if (!chatById.isEmpty()) { List hits = messageMapper.selectList( Wrappers.lambdaQuery() .in(Message::getChatId, chatById.keySet()) .like(Message::getContent, kw) .orderByAsc(Message::getId)); for (Message m : hits) { contentHits.putIfAbsent(m.getChatId(), m); } } // 合并:按「会话最近活跃时间倒序」输出,标题命中优先于内容命中 List result = new ArrayList<>(); for (Chat c : chats) { boolean byTitle = titleHits.contains(c.getId()); Message byContent = contentHits.get(c.getId()); if (!byTitle && byContent == null) { continue; } ChatDTO dto = toDto(c, null, null); dto.setMatchType(byTitle && byContent != null ? "both" : byTitle ? "title" : "message"); if (byContent != null) { dto.setMatchSnippet(buildSnippet(byContent.getContent(), kw)); } result.add(dto); if (result.size() >= max) { break; } } // 数量信息:会话数用轻量查询补齐,避免 N+1 if (!result.isEmpty()) { List ids = result.stream().map(ChatDTO::getId).toList(); Map counts = messageMapper.selectList( Wrappers.lambdaQuery() .select(Message::getChatId) .in(Message::getChatId, ids)) .stream() .collect(Collectors.groupingBy(Message::getChatId, Collectors.counting())); for (ChatDTO dto : result) { dto.setMessageCount(counts.getOrDefault(dto.getId(), 0L)); } } log.debug("会话搜索 userId={} 关键词={} 标题命中={} 内容命中={} 返回={}", userId, kw, titleHits.size(), contentHits.size(), result.size()); return result; } /** * 围绕关键词截取一段用于展示的片段。 * *

把关键词居中,前后各留 {@code CONTEXT} 个字符,两侧加省略号。 * 命中位置在很长的消息里时,这比返回消息开头更有助于用户辨认。 */ private String buildSnippet(String content, String keyword) { if (content == null || content.isBlank()) { return ""; } String flat = content.replaceAll("\\s+", " ").trim(); int index = flat.toLowerCase(Locale.ROOT).indexOf(keyword.toLowerCase(Locale.ROOT)); if (index < 0) { return abbreviate(flat, SNIPPET_LENGTH); } int start = Math.max(0, index - CONTEXT_LENGTH); int end = Math.min(flat.length(), index + keyword.length() + CONTEXT_LENGTH); String snippet = flat.substring(start, end); return (start > 0 ? "…" : "") + snippet + (end < flat.length() ? "…" : ""); } private String abbreviate(String text, int max) { return text.length() <= max ? text : text.substring(0, max) + "…"; } // ==================== 内部辅助 ==================== /** 序列化 meta;传入 null 时返回 null(列可为空) */ private String writeMeta(ChatMetaRequest meta) { if (meta == null) { return null; } try { return objectMapper.writeValueAsString(meta); } catch (Exception e) { throw BusinessException.badRequest("模型参数格式不正确: " + e.getMessage()); } } private ChatDTO toDto(Chat chat, Long messageCount, List collections) { ChatDTO dto = new ChatDTO(); dto.setId(chat.getId()); dto.setTitle(chat.getTitle()); // meta 列可能为 NULL,而 @JsonRawValue 遇到 null 会输出字面量 null, // 因此统一兜底成 {} 让前端可以无脑取字段 dto.setMeta(chat.getMeta() == null || chat.getMeta().isBlank() ? "{}" : chat.getMeta()); dto.setCreatedAt(chat.getCreatedAt()); dto.setUpdatedAt(chat.getUpdatedAt()); dto.setMessageCount(messageCount == null ? 0L : messageCount); dto.setCollectionNames(collections == null ? new ArrayList<>() : collections); return dto; } }