kongdeqiang
2026-10-09 9af621d181217a03b1b3dce208a163915db974a3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
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<ChatDTO> listByUser(Long userId) {
        List<Chat> chats = chatMapper.selectList(
                Wrappers.<Chat>lambdaQuery()
                        .eq(Chat::getUserId, userId)
                        .orderByDesc(Chat::getUpdatedAt));
        if (chats.isEmpty()) {
            return Collections.emptyList();
        }
 
        // 一次性聚合消息数,避免在循环里对每个会话查一次(N+1 查询)
        List<Long> chatIds = chats.stream().map(Chat::getId).toList();
        Map<Long, Long> countByChat = messageMapper.selectList(
                        Wrappers.<Message>lambdaQuery()
                                .select(Message::getChatId)
                                .in(Message::getChatId, chatIds))
                .stream()
                .collect(Collectors.groupingBy(Message::getChatId, Collectors.counting()));
 
        // 同样一次性取出所有会话的知识库绑定
        Map<Long, List<String>> collectionsByChat = chatCollectionMapper.selectList(
                        Wrappers.<ChatCollection>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.<Message>lambdaQuery().eq(Message::getChatId, chatId));
        List<String> collections = chatCollectionMapper.selectList(
                        Wrappers.<ChatCollection>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.<Message>lambdaQuery().eq(Message::getChatId, chatId));
        chatCollectionMapper.delete(
                Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId));
 
        // 会话绑定的文件解除会话绑定(文件本体与向量集合保留,用户可继续在别处使用)
        List<UploadFile> boundFiles = uploadFileMapper.selectList(
                Wrappers.<UploadFile>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<ChatDTO> 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<Chat> chats = chatMapper.selectList(
                Wrappers.<Chat>lambdaQuery()
                        .eq(Chat::getUserId, userId)
                        .orderByDesc(Chat::getUpdatedAt));
        if (chats.isEmpty()) {
            return Collections.emptyList();
        }
 
        Map<Long, Chat> chatById = new LinkedHashMap<>();
        for (Chat c : chats) {
            chatById.put(c.getId(), c);
        }
 
        // 命中标题的会话
        Set<Long> 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<Long, Message> contentHits = new LinkedHashMap<>();
        if (!chatById.isEmpty()) {
            List<Message> hits = messageMapper.selectList(
                    Wrappers.<Message>lambdaQuery()
                            .in(Message::getChatId, chatById.keySet())
                            .like(Message::getContent, kw)
                            .orderByAsc(Message::getId));
            for (Message m : hits) {
                contentHits.putIfAbsent(m.getChatId(), m);
            }
        }
 
        // 合并:按「会话最近活跃时间倒序」输出,标题命中优先于内容命中
        List<ChatDTO> 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<Long> ids = result.stream().map(ChatDTO::getId).toList();
            Map<Long, Long> counts = messageMapper.selectList(
                            Wrappers.<Message>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;
    }
 
    /**
     * 围绕关键词截取一段用于展示的片段。
     *
     * <p>把关键词居中,前后各留 {@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<String> 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;
    }
}