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;
/**
* 临时附件文本暂存的内存实现。
*
*
设计考量见 {@link PendingAttachmentService} 的类注释。这里补充实现细节:
*
* - 带 TTL:默认 30 分钟。用户上传图片后可能过一会儿才发送,
* 也可能干脆不发了,过期自动清理避免内存堆积。
* - 单条大小上限:防止有人塞一篇小说进来撑爆堆内存。
* - 归属校验:id 是随机串,但仍校验 userId ——
* 万一 id 泄漏,也无法读到别人的内容。
* - 取一次即失效:附件文本只在发送那一次需要,
* 消费后立即释放。
*
*/
@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 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 consumeAll(Long userId, List ids) {
List 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);
}
}