kongdeqiang
2026-10-12 ccf1a44c001e233c158bd168dc2d0d96721af929
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
package com.custom.webui.service.impl;
 
import com.custom.webui.service.PendingAttachmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
 
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * 临时附件文本暂存的内存实现。
 *
 * <p>设计考量见 {@link PendingAttachmentService} 的类注释。这里补充实现细节:
 * <ul>
 *   <li><b>带 TTL</b>:默认 30 分钟。用户上传图片后可能过一会儿才发送,
 *       也可能干脆不发了,过期自动清理避免内存堆积。</li>
 *   <li><b>单条大小上限</b>:防止有人塞一篇小说进来撑爆堆内存。</li>
 *   <li><b>归属校验</b>:id 是随机串,但仍校验 userId ——
 *       万一 id 泄漏,也无法读到别人的内容。</li>
 *   <li><b>取一次即失效</b>:附件文本只在发送那一次需要,
 *       消费后立即释放。</li>
 * </ul>
 */
@Slf4j
@Service
public class PendingAttachmentServiceImpl implements PendingAttachmentService {
 
    /** 单条文本上限,比 llm.per-part-char-limit 宽松些,最终由它再裁 */
    @Value("${webui.attachment.max-char-length:20000}")
    private int maxCharLength = 20000;
 
    /** 存活时长(毫秒),默认 30 分钟 */
    @Value("${webui.attachment.ttl-millis:1800000}")
    private long ttlMillis = 1_800_000L;
 
    private final Map<String, Entry> store = new ConcurrentHashMap<>();
    private final SecureRandom random = new SecureRandom();
 
    /**
     * 单条暂存记录。
     *
     * @param userId    归属用户
     * @param text      文本
     * @param expiresAt 过期时间戳
     */
    private record Entry(Long userId, String text, long expiresAt) {
        boolean expired() {
            return System.currentTimeMillis() > expiresAt;
        }
    }
 
    @Override
    public String store(Long userId, String text) {
        if (text == null || text.isEmpty()) {
            return null;
        }
        String normalized = text.length() > maxCharLength
                ? text.substring(0, maxCharLength)
                : text;
 
        String id = newId();
        store.put(id, new Entry(userId, normalized, System.currentTimeMillis() + ttlMillis));
        log.debug("暂存附件文本 id={} userId={} 字符={}", id, userId, normalized.length());
        return id;
    }
 
    @Override
    public String consume(Long userId, String id) {
        if (id == null || id.isBlank()) {
            return null;
        }
        Entry entry = store.remove(id);
        if (entry == null) {
            log.debug("附件文本不存在或已被消费 id={}", id);
            return null;
        }
        if (entry.expired()) {
            log.debug("附件文本已过期 id={}", id);
            return null;
        }
        if (!entry.userId().equals(userId)) {
            // 不区分「不存在」与「无权」,避免探测他人 id 是否有效
            log.warn("附件文本归属不匹配,已拒绝 id={} 请求者={} 归属={}", id, userId, entry.userId());
            return null;
        }
        return entry.text();
    }
 
    @Override
    public List<String> consumeAll(Long userId, List<String> ids) {
        List<String> texts = new ArrayList<>();
        if (ids == null) {
            return texts;
        }
        for (String id : ids) {
            String text = consume(userId, id);
            if (text != null && !text.isBlank()) {
                texts.add(text);
            }
        }
        return texts;
    }
 
    @Override
    @Scheduled(fixedDelay = 300_000L, initialDelay = 300_000L)
    public int evictExpired() {
        int before = store.size();
        store.entrySet().removeIf(e -> e.getValue().expired());
        int removed = before - store.size();
        if (removed > 0) {
            log.debug("清理过期附件文本 {} 条,剩余 {} 条", removed, store.size());
        }
        return removed;
    }
 
    @Override
    public int size() {
        return store.size();
    }
 
    /** 生成 URL 安全的短随机 id(16 字节 base64url,约 22 字符) */
    private String newId() {
        byte[] bytes = new byte[16];
        random.nextBytes(bytes);
        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
    }
}