微信审核回调改为先落库后应答并异步探测补偿
自动发布开发环境 Nacos 配置 / publish (push) Successful in 24s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 8s

- 回调到达即持久化解密报文与 trace_id,落库失败返回 500 让微信重试
- 异步执行器按环境顺序探测认领,状态机 PENDING/PROCESSING/SUCCESS/NO_ENV/FAILED/DEAD
- 定时补偿按 30/120/600/3600 秒退避,达到上限置 DEAD 并告警,启动时恢复未完成任务
- 数据库条件更新抢锁保证多实例只处理一次,新增 V22 迁移与管理端重试配置/明细
This commit is contained in:
2026-11-07 13:02:26 +08:00
parent 69a32672c9
commit e870285300
14 changed files with 798 additions and 310 deletions
@@ -2,7 +2,6 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties;
import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService;
@@ -79,7 +78,8 @@ public class WechatContentModerationCallbackController {
@RequestHeader(value = "X-Timestamp", required = false) String forwardTimestamp,
@RequestHeader(value = "X-Nonce", required = false) String forwardNonce,
@RequestHeader(value = "X-Signature", required = false) String forwardSignature,
@RequestBody String body) throws Exception {
@RequestBody String body,
javax.servlet.http.HttpServletResponse response) throws Exception {
if (StringUtils.hasText(forwardBy) || StringUtils.hasText(forwardHop)) {
return handleForwardedCallback(forwardBy, forwardHop, forwardTimestamp, forwardNonce, forwardSignature, body);
}
@@ -97,31 +97,16 @@ public class WechatContentModerationCallbackController {
throw new IllegalArgumentException("微信审核回调仅接受 AES 加密消息");
}
String decoded = crypto.decrypt(encrypted, config.getEncodingAesKey(), wechatProperties.getAppId());
ParsedCallback parsed = parsePayload(decoded);
if (!StringUtils.hasText(parsed.traceId())) throw new IllegalArgumentException("微信审核回调缺少任务标识");
if (!contentModerationForwardService.reserveTrace(parsed.traceId())) {
log.info("微信审核回调重复到达,按幂等直接结束,traceId={}", parsed.traceId());
return "success";
}
boolean localHit;
Long taskId;
try {
localHit = claimLocally(parsed);
taskId = contentModerationForwardService.persistCallback(decoded);
} catch (RuntimeException exception) {
contentModerationForwardService.releaseTrace(parsed.traceId());
throw exception;
}
if (localHit) {
return "success";
}
try {
boolean claimed = contentModerationForwardService.probeAndForward(
parsed.traceId(), decoded, buildAuditPayload(parsed));
if (!claimed) contentModerationForwardService.releaseTrace(parsed.traceId());
} catch (RuntimeException exception) {
contentModerationForwardService.releaseTrace(parsed.traceId());
throw exception;
response.setStatus(500);
log.error("微信审核回调落库失败,拒绝返回成功等待微信重试,errorType={}",
exception.getClass().getSimpleName());
return "persist_failed";
}
contentModerationForwardService.submit(taskId);
return "success";
}
@@ -211,14 +196,6 @@ public class WechatContentModerationCallbackController {
return new ParsedCallback(traceId, suggest, reason);
}
private String buildAuditPayload(ParsedCallback parsed) {
ObjectNode payload = objectMapper.createObjectNode();
payload.put("trace_id", parsed.traceId());
payload.put("suggest", parsed.suggest());
payload.put("reason", parsed.reason());
return payload.toString();
}
private String normalizeEnv(String value) {
if (!StringUtils.hasText(value)) return null;
String normalized = value.trim().toLowerCase(Locale.ROOT);
@@ -6,7 +6,7 @@ import com.xiaowang.jayucloud.salon.core.modules.system.vo.ModerationForwardReco
import java.util.List;
/**
* 微信异步图片审核回调的跨环境串行探测认领。
* 微信异步图片审核回调的持久化任务、跨环境串行探测与补偿。
*/
public interface ContentModerationForwardService {
@@ -15,27 +15,41 @@ public interface ContentModerationForwardService {
List<ModerationForwardRecordVO> listRecent(int limit);
/**
* 处理前占位,保证同一个 trace_id 只处理一次。
*
* @return true 表示本次成功占位,可以继续处理;false 表示重复到达
* 回调到达后第一件事:按 trace_id 落库。重复回调直接返回已有任务 ID。
* 落库失败抛出异常,由控制器返回非 200,让微信重试。
*/
Long persistCallback(String rawPayload);
/**
* 提交异步执行,不影响回调响应耗时。
*/
void submit(Long taskId);
/**
* 执行一次任务:抢锁、幂等判断、本地认领、串行探测、写回状态。
*/
void executeTask(Long taskId);
/**
* 补偿扫描:把到期或锁超时的任务重新提交执行。
*/
int retryDueTasks();
/**
* 应用启动时扫描未完成任务,避免进程重启丢消息。
*/
int recoverPendingTasks();
/**
* 处理前占位,保证同一个 trace_id 的业务处理只成功一次。
*/
boolean reserveTrace(String traceId);
/**
* 释放占位,允许微信或其它环境后续重试。
* 释放占位,允许后续重试继续处理。
*/
void releaseTrace(String traceId);
/**
* 本地未命中后,按配置顺序串行探测其它环境。
*
* @param traceId 微信审核任务标识
* @param rawPayload 原始解密后的回调报文,原样转发
* @param auditPayload 脱敏后的审计摘要,仅落库用于排查
* @return true 表示某个目标环境已认领并处理
*/
boolean probeAndForward(String traceId, String rawPayload, String auditPayload);
/**
* 校验转发请求的 HMAC 签名、时间窗与 nonce 防重放。
*/
@@ -1,22 +1,32 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationForwardHttpClient;
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationProbeResult;
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto;
import com.xiaowang.jayucloud.salon.core.modules.system.entity.ModerationCallbackForwardDO;
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.ModerationCallbackForwardMapper;
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig;
import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService;
import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService;
import com.xiaowang.jayucloud.salon.core.modules.system.vo.ModerationForwardRecordVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
@@ -26,16 +36,25 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
@Service
@RequiredArgsConstructor
public class ContentModerationForwardServiceImpl implements ContentModerationForwardService {
private static final String STATUS_CLAIMED = "CLAIMED";
private static final String STATUS_PENDING = "PENDING";
private static final String STATUS_PROCESSING = "PROCESSING";
private static final String STATUS_SUCCESS = "SUCCESS";
private static final String STATUS_NO_ENV = "NO_ENV";
private static final String STATUS_FAILED = "FAILED";
private static final String STATUS_DEAD = "DEAD";
private static final long SIGNATURE_WINDOW_SECONDS = 300;
private static final long NONCE_TTL_SECONDS = 600;
private static final long LOCK_TIMEOUT_SECONDS = 600;
private static final Duration CLAIM_TTL = Duration.ofMinutes(30);
private static final String NONCE_KEY_PREFIX = "salon:content-moderation:forward:nonce:";
private static final String CLAIM_KEY_PREFIX = "salon:content-moderation:claim:";
@@ -45,11 +64,27 @@ public class ContentModerationForwardServiceImpl implements ContentModerationFor
private static final String NONCE_HEADER = "X-Nonce";
private static final String SIGNATURE_HEADER = "X-Signature";
private static final AtomicInteger THREAD_INDEX = new AtomicInteger(1);
private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(4, new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "moderation-callback-" + THREAD_INDEX.getAndIncrement());
thread.setDaemon(true);
return thread;
}
});
private final ModerationCallbackForwardMapper forwardMapper;
private final SecureIntegrationConfigService secureIntegrationConfigService;
private final SalonDeployProperties deployProperties;
private final RedisTemplate<String, Object> redisTemplate;
private final ModerationForwardHttpClient forwardHttpClient;
private final IntegrationProbeService integrationProbeService;
private final ContentModerationService contentModerationService;
private final ObjectMapper objectMapper;
private final WechatCallbackCrypto crypto;
private final String instanceId = UUID.randomUUID().toString().replace("-", "");
@Override
public ModerationForwardConfig runtimeConfig() {
@@ -65,6 +100,104 @@ public class ContentModerationForwardServiceImpl implements ContentModerationFor
return rows.stream().map(this::toVO).toList();
}
@Override
public Long persistCallback(String rawPayload) {
String traceId;
String untracedNote = null;
try {
ParsedPayload parsed = parsePayload(rawPayload);
traceId = parsed.traceId();
} catch (RuntimeException exception) {
traceId = null;
}
if (!StringUtils.hasText(traceId)) {
traceId = "untraced-" + sha256Hex(rawPayload == null ? "" : rawPayload).substring(0, 24);
untracedNote = "回调缺少 trace_id 或报文无法解析,已置为 DEAD 等待人工排查";
}
ModerationCallbackForwardDO existing = findByTrace(traceId);
if (existing != null) {
log.info("微信审核回调已存在任务,按幂等返回,traceId={}, status={}", traceId, existing.getStatus());
return existing.getId();
}
LocalDateTime now = LocalDateTime.now();
ModerationCallbackForwardDO row = new ModerationCallbackForwardDO();
row.setTraceId(traceId);
row.setSourceEnv(deployProperties.getEnv());
row.setPayload(rawPayload);
if (untracedNote == null) {
row.setStatus(STATUS_PENDING);
row.setRetryCount(0);
row.setNextAttemptAt(now);
} else {
row.setStatus(STATUS_DEAD);
row.setRetryCount(0);
row.setLastError(untracedNote);
row.setFinishedAt(now);
}
row.setCreatedAt(now);
row.setUpdatedAt(now);
try {
forwardMapper.insert(row);
} catch (DuplicateKeyException exception) {
ModerationCallbackForwardDO duplicated = findByTrace(traceId);
if (duplicated == null) throw exception;
log.info("微信审核回调并发重复落库,按幂等返回,traceId={}", traceId);
return duplicated.getId();
}
if (untracedNote != null) {
log.error("MODERATION_CALLBACK_UNTRACED traceId={}, sourceEnv={}, payloadLength={}, note={}",
traceId, deployProperties.getEnv(), rawPayload == null ? 0 : rawPayload.length(), untracedNote);
}
return row.getId();
}
@Override
public void submit(Long taskId) {
if (taskId == null) return;
EXECUTOR.execute(() -> executeTask(taskId));
}
@Override
public void executeTask(Long taskId) {
if (taskId == null) return;
ModerationCallbackForwardDO snapshot = forwardMapper.selectById(taskId);
if (snapshot == null || isTerminal(snapshot.getStatus())) return;
String owner = deployProperties.getEnv() + "-" + instanceId;
if (!claimTask(taskId, owner)) {
log.info("微信审核回调任务已被其它实例占用或未到执行时间,taskId={}", taskId);
return;
}
ModerationCallbackForwardDO row = forwardMapper.selectById(taskId);
if (row == null) return;
try {
process(row, owner);
} catch (RuntimeException exception) {
log.error("微信审核回调异步处理异常,taskId={}, traceId={}, errorType={}",
taskId, row.getTraceId(), exception.getClass().getSimpleName());
releaseTrace(row.getTraceId());
failOrRetry(row, owner, "异步处理异常:" + exception.getClass().getSimpleName(), true);
}
}
@Override
@Scheduled(fixedDelayString = "${salon.moderation-forward.retry-scan-ms:30000}")
public int retryDueTasks() {
return dispatchDueTasks(50);
}
@Override
public int recoverPendingTasks() {
return dispatchDueTasks(100);
}
@EventListener(ApplicationReadyEvent.class)
public void recoverOnStartup() {
int recovered = recoverPendingTasks();
if (recovered > 0) {
log.info("微信审核回调启动补偿扫描完成,提交任务数={}", recovered);
}
}
@Override
public boolean reserveTrace(String traceId) {
if (!StringUtils.hasText(traceId)) return false;
@@ -88,61 +221,6 @@ public class ContentModerationForwardServiceImpl implements ContentModerationFor
}
}
@Override
public boolean probeAndForward(String traceId, String rawPayload, String auditPayload) {
String localEnv = deployProperties.getEnv();
ModerationForwardConfig config = runtimeConfig();
if (!config.ready()) {
recordOutcome(traceId, null, auditPayload, STATUS_NO_ENV, "跨环境转发未启用或共享密钥缺失");
log.error("MODERATION_FORWARD_NO_ENV traceId={}, sourceEnv={}, order=[], results=未启用或共享密钥缺失",
traceId, localEnv);
return false;
}
List<String> envs = config.orderedTargets(localEnv);
if (envs.isEmpty()) {
recordOutcome(traceId, null, auditPayload, STATUS_NO_ENV, "未配置可用的目标环境地址");
log.error("MODERATION_FORWARD_NO_ENV traceId={}, sourceEnv={}, order=[], results=未配置可用的目标环境地址",
traceId, localEnv);
return false;
}
List<String> results = new ArrayList<>();
List<String> erroredEnvs = new ArrayList<>();
String claimedEnv = null;
for (String env : envs) {
String target = config.targetFor(env);
ModerationProbeResult result;
try {
result = forwardHttpClient.probe(target, rawPayload, buildHeaders(config, localEnv, rawPayload));
} catch (RuntimeException exception) {
result = ModerationProbeResult.ERROR;
}
results.add(env + "=" + result.name());
if (result == ModerationProbeResult.CLAIMED) {
claimedEnv = env;
break;
}
if (result == ModerationProbeResult.ERROR) erroredEnvs.add(env);
}
if (!erroredEnvs.isEmpty()) {
log.error("MODERATION_FORWARD_TARGET_ERROR traceId={}, sourceEnv={}, order={}, erroredEnvs={}, results={}",
traceId, localEnv, envs, erroredEnvs, results);
}
if (claimedEnv != null) {
String note = erroredEnvs.isEmpty() ? null : "部分环境未正常应答:" + erroredEnvs;
recordOutcome(traceId, claimedEnv, auditPayload, STATUS_CLAIMED, note);
log.info("微信审核回调跨环境认领成功,traceId={}, sourceEnv={}, targetEnv={}, results={}",
traceId, localEnv, claimedEnv, results);
return true;
}
String note = "无环境认领;尝试顺序=" + envs + ",结果=" + results;
recordOutcome(traceId, null, auditPayload, STATUS_NO_ENV, note);
log.error("MODERATION_FORWARD_NO_ENV traceId={}, sourceEnv={}, order={}, results={}",
traceId, localEnv, envs, results);
return false;
}
@Override
public boolean verifySignature(String timestamp, String nonce, String signature, String body) {
if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) return false;
@@ -161,6 +239,189 @@ public class ContentModerationForwardServiceImpl implements ContentModerationFor
signature.trim().toLowerCase(java.util.Locale.ROOT).getBytes(StandardCharsets.UTF_8));
}
@PreDestroy
public void shutdown() {
EXECUTOR.shutdown();
}
private void process(ModerationCallbackForwardDO row, String owner) {
ParsedPayload parsed = parsePayload(row.getPayload());
String traceId = row.getTraceId();
if (!reserveTrace(traceId)) {
finishSuccess(row, owner, row.getSourceEnv(), "幂等短路:本环境已处理");
return;
}
boolean localHit;
try {
localHit = claimLocally(parsed);
} catch (RuntimeException exception) {
releaseTrace(traceId);
throw exception;
}
if (localHit) {
finishSuccess(row, owner, deployProperties.getEnv(), null);
return;
}
ModerationForwardConfig config = runtimeConfig();
if (!config.ready()) {
releaseTrace(traceId);
failOrRetry(row, owner, "跨环境转发未启用或共享密钥缺失", false);
return;
}
List<String> envs = config.orderedTargets(deployProperties.getEnv());
if (envs.isEmpty()) {
releaseTrace(traceId);
failOrRetry(row, owner, "未配置可用的目标环境地址", false);
return;
}
List<String> results = new ArrayList<>();
List<String> erroredEnvs = new ArrayList<>();
String claimedEnv = null;
for (String env : envs) {
ModerationProbeResult result;
try {
result = forwardHttpClient.probe(config.targetFor(env), row.getPayload(),
buildHeaders(config, deployProperties.getEnv(), row.getPayload()));
} catch (RuntimeException exception) {
result = ModerationProbeResult.ERROR;
}
results.add(env + "=" + result.name());
if (result == ModerationProbeResult.CLAIMED) {
claimedEnv = env;
break;
}
if (result == ModerationProbeResult.ERROR) erroredEnvs.add(env);
}
if (!erroredEnvs.isEmpty()) {
log.error("MODERATION_FORWARD_TARGET_ERROR traceId={}, sourceEnv={}, order={}, erroredEnvs={}, results={}",
traceId, deployProperties.getEnv(), envs, erroredEnvs, results);
}
if (claimedEnv != null) {
String note = erroredEnvs.isEmpty() ? null : "部分环境未正常应答:" + erroredEnvs;
finishSuccess(row, owner, claimedEnv, note);
return;
}
releaseTrace(traceId);
boolean anyError = !erroredEnvs.isEmpty();
failOrRetry(row, owner, "无环境认领;尝试顺序=" + envs + ",结果=" + results, anyError);
}
private void finishSuccess(ModerationCallbackForwardDO row, String owner, String targetEnv, String note) {
LocalDateTime now = LocalDateTime.now();
applyOutcome(row.getId(), owner, STATUS_SUCCESS, targetEnv,
row.getRetryCount() == null ? 0 : row.getRetryCount(), note, null, now);
log.info("微信审核回调任务处理成功,traceId={}, sourceEnv={}, targetEnv={}, taskId={}",
row.getTraceId(), row.getSourceEnv(), targetEnv, row.getId());
}
private void failOrRetry(ModerationCallbackForwardDO row, String owner, String note, boolean error) {
ModerationForwardConfig config = runtimeConfig();
int maxRetry = config.getMaxRetry() <= 0 ? ModerationForwardConfig.DEFAULT_MAX_RETRY : config.getMaxRetry();
int retryCount = (row.getRetryCount() == null ? 0 : row.getRetryCount()) + 1;
LocalDateTime now = LocalDateTime.now();
if (retryCount > maxRetry) {
applyOutcome(row.getId(), owner, STATUS_DEAD, null, retryCount, note, null, now);
log.error("MODERATION_CALLBACK_DEAD traceId={}, sourceEnv={}, taskId={}, retryCount={}, lastError={}",
row.getTraceId(), row.getSourceEnv(), row.getId(), retryCount, note);
return;
}
long delaySeconds = config.backoffSecondsFor(retryCount);
LocalDateTime nextAttemptAt = now.plusSeconds(delaySeconds);
applyOutcome(row.getId(), owner, error ? STATUS_FAILED : STATUS_NO_ENV, null,
retryCount, note, nextAttemptAt, null);
log.warn("微信审核回调任务待补偿,traceId={}, sourceEnv={}, taskId={}, retryCount={}, nextAttemptAt={}, lastError={}",
row.getTraceId(), row.getSourceEnv(), row.getId(), retryCount, nextAttemptAt, note);
}
private void applyOutcome(Long taskId, String owner, String status, String targetEnv, int retryCount,
String lastError, LocalDateTime nextAttemptAt, LocalDateTime finishedAt) {
UpdateWrapper<ModerationCallbackForwardDO> wrapper = new UpdateWrapper<>();
wrapper.eq("id", taskId)
.eq("locked_by", owner)
.set("status", status)
.set("target_env", StringUtils.hasText(targetEnv) ? targetEnv : null)
.set("retry_count", retryCount)
.set("last_error", clip(lastError, 500))
.set("next_attempt_at", nextAttemptAt)
.set("finished_at", finishedAt)
.set("locked_by", null)
.set("locked_at", null)
.set("updated_at", LocalDateTime.now());
if (forwardMapper.update(null, wrapper) <= 0) {
log.warn("微信审核回调任务写回失败或锁已丢失,taskId={}, targetStatus={}", taskId, status);
}
}
private boolean claimTask(Long taskId, String owner) {
LocalDateTime now = LocalDateTime.now();
UpdateWrapper<ModerationCallbackForwardDO> wrapper = new UpdateWrapper<>();
wrapper.eq("id", taskId)
.apply("(status IN ('PENDING','RETRY','NO_ENV','FAILED','TARGET_MISSING') "
+ "OR (status = 'PROCESSING' AND locked_at < {0}))", now.minusSeconds(LOCK_TIMEOUT_SECONDS))
.apply("(next_attempt_at IS NULL OR next_attempt_at <= {0})", now)
.set("status", STATUS_PROCESSING)
.set("locked_by", owner)
.set("locked_at", now)
.set("updated_at", now);
return forwardMapper.update(null, wrapper) > 0;
}
private int dispatchDueTasks(int limit) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime staleBefore = now.minusSeconds(LOCK_TIMEOUT_SECONDS);
List<ModerationCallbackForwardDO> rows = forwardMapper.selectList(
new LambdaQueryWrapper<ModerationCallbackForwardDO>()
.apply("(status IN ('PENDING','RETRY','NO_ENV','FAILED','TARGET_MISSING') "
+ "OR (status = 'PROCESSING' AND locked_at < {0}))", staleBefore)
.apply("(next_attempt_at IS NULL OR next_attempt_at <= {0})", now)
.orderByAsc(ModerationCallbackForwardDO::getId)
.last("LIMIT " + limit));
int dispatched = 0;
for (ModerationCallbackForwardDO row : rows) {
submit(row.getId());
dispatched++;
}
return dispatched;
}
private boolean claimLocally(ParsedPayload parsed) {
if (integrationProbeService.handleImageCallback(parsed.traceId(), parsed.suggest(), null)) {
return true;
}
return contentModerationService.handleWechatImageResult(
parsed.traceId(), parsed.suggest(), parsed.reason());
}
private ParsedPayload parsePayload(String decoded) {
if (!StringUtils.hasText(decoded)) {
throw new IllegalArgumentException("审核回调报文为空");
}
try {
if (decoded.trim().startsWith("<")) {
String traceId = firstNonBlank(crypto.value(decoded, "trace_id"),
crypto.value(decoded, "TraceId"), crypto.value(decoded, "task_id"));
String suggest = firstNonBlank(crypto.value(decoded, "suggest"),
crypto.value(decoded, "Suggest"), "review");
String reason = firstNonBlank(crypto.value(decoded, "errmsg"),
crypto.value(decoded, "label"), "微信异步图片审核回调");
return new ParsedPayload(traceId, suggest, reason);
}
JsonNode root = objectMapper.readTree(decoded);
String traceId = firstText(root, "trace_id", "traceId", "task_id");
String suggest = firstText(root.path("result"), "suggest", "Suggest");
if (!StringUtils.hasText(suggest)) suggest = firstText(root, "suggest", "Suggest");
if (!StringUtils.hasText(suggest)) suggest = "review";
String reason = firstText(root, "errmsg", "reason");
if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调";
return new ParsedPayload(traceId, suggest, reason);
} catch (Exception exception) {
throw new IllegalArgumentException("审核回调报文无法解析", exception);
}
}
private Map<String, String> buildHeaders(ModerationForwardConfig config, String sourceEnv, String payload) {
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
String nonce = UUID.randomUUID().toString().replace("-", "");
@@ -174,21 +435,6 @@ public class ContentModerationForwardServiceImpl implements ContentModerationFor
return headers;
}
private void recordOutcome(String traceId, String targetEnv, String auditPayload, String status, String note) {
if (!StringUtils.hasText(traceId)) return;
ModerationCallbackForwardDO existing = findByTrace(traceId);
if (existing != null) {
existing.setTargetEnv(targetEnv);
existing.setPayload(auditPayload);
existing.setStatus(status);
existing.setLastError(clip(note, 500));
existing.setUpdatedAt(LocalDateTime.now());
forwardMapper.updateById(existing);
return;
}
saveQuietly(build(traceId, deployProperties.getEnv(), targetEnv, auditPayload, status, note));
}
private boolean reserveNonce(String nonce) {
try {
Boolean fresh = redisTemplate.opsForValue().setIfAbsent(NONCE_KEY_PREFIX + nonce, "1",
@@ -226,32 +472,6 @@ public class ContentModerationForwardServiceImpl implements ContentModerationFor
return builder.toString();
}
private ModerationCallbackForwardDO build(String traceId, String sourceEnv, String targetEnv,
String payload, String status, String error) {
LocalDateTime now = LocalDateTime.now();
ModerationCallbackForwardDO row = new ModerationCallbackForwardDO();
row.setTraceId(clip(traceId, 128));
row.setSourceEnv(clip(sourceEnv, 16));
row.setTargetEnv(StringUtils.hasText(targetEnv) ? clip(targetEnv, 16) : null);
row.setPayload(payload);
row.setStatus(status);
row.setRetryCount(0);
row.setLastError(clip(error, 500));
row.setCreatedAt(now);
row.setUpdatedAt(now);
return row;
}
private boolean saveQuietly(ModerationCallbackForwardDO row) {
try {
forwardMapper.insert(row);
return true;
} catch (DuplicateKeyException exception) {
log.info("微信审核回调转发记录已存在,traceId={}", row.getTraceId());
return false;
}
}
private ModerationCallbackForwardDO findByTrace(String traceId) {
if (!StringUtils.hasText(traceId)) return null;
return forwardMapper.selectOne(new LambdaQueryWrapper<ModerationCallbackForwardDO>()
@@ -259,6 +479,10 @@ public class ContentModerationForwardServiceImpl implements ContentModerationFor
.last("LIMIT 1"));
}
private boolean isTerminal(String status) {
return STATUS_SUCCESS.equals(status) || STATUS_DEAD.equals(status);
}
private ModerationForwardRecordVO toVO(ModerationCallbackForwardDO row) {
ModerationForwardRecordVO vo = new ModerationForwardRecordVO();
vo.setId(row.getId());
@@ -268,14 +492,30 @@ public class ContentModerationForwardServiceImpl implements ContentModerationFor
vo.setStatus(row.getStatus());
vo.setRetryCount(row.getRetryCount());
vo.setLastError(row.getLastError());
vo.setPayload(row.getPayload());
vo.setNextAttemptAt(row.getNextAttemptAt());
vo.setFinishedAt(row.getFinishedAt());
vo.setCreatedAt(row.getCreatedAt());
vo.setUpdatedAt(row.getUpdatedAt());
return vo;
}
private String firstText(JsonNode node, String... keys) {
for (String key : keys) if (node != null && node.hasNonNull(key)) return node.path(key).asText();
return null;
}
private String firstNonBlank(String... values) {
for (String value : values) if (StringUtils.hasText(value)) return value;
return null;
}
private String clip(String value, int max) {
if (!StringUtils.hasText(value)) return null;
String trimmed = value.trim();
return trimmed.length() <= max ? trimmed : trimmed.substring(0, max);
}
private record ParsedPayload(String traceId, String suggest, String reason) {
}
}
@@ -28,4 +28,8 @@ public class SecureIntegrationConfigDTO {
private List<String> moderationForwardOrder;
private String moderationForwardSecret;
private Boolean clearModerationForwardSecret;
/** 补偿最大重试次数(1-10),未填写使用默认值。 */
private Integer moderationForwardMaxRetry;
/** 补偿指数退避秒数梯度,未填写使用默认 30/120/600/3600。 */
private List<Integer> moderationForwardBackoffSeconds;
}
@@ -43,4 +43,16 @@ public class ModerationCallbackForwardDO {
@TableField("updated_at")
private LocalDateTime updatedAt;
@TableField("next_attempt_at")
private LocalDateTime nextAttemptAt;
@TableField("locked_by")
private String lockedBy;
@TableField("locked_at")
private LocalDateTime lockedAt;
@TableField("finished_at")
private LocalDateTime finishedAt;
}
@@ -5,6 +5,7 @@ import lombok.Data;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -12,13 +13,20 @@ import java.util.Map;
@Data
@AllArgsConstructor
public class ModerationForwardConfig {
public static final int DEFAULT_MAX_RETRY = 4;
public static final List<Long> DEFAULT_BACKOFF_SECONDS =
Collections.unmodifiableList(Arrays.asList(30L, 120L, 600L, 3600L));
private boolean enabled;
private Map<String, String> targets;
private String secret;
private List<String> order;
private int maxRetry;
private List<Long> backoffSeconds;
public static ModerationForwardConfig disabled() {
return new ModerationForwardConfig(false, Collections.emptyMap(), "", Collections.emptyList());
return new ModerationForwardConfig(false, Collections.emptyMap(), "", Collections.emptyList(),
DEFAULT_MAX_RETRY, DEFAULT_BACKOFF_SECONDS);
}
public String targetFor(String env) {
@@ -48,4 +56,14 @@ public class ModerationForwardConfig {
}
return result;
}
/**
* 第 retryCount 次失败后的等待秒数(retryCount 从 1 开始)。
*/
public long backoffSecondsFor(int retryCount) {
List<Long> values = backoffSeconds == null || backoffSeconds.isEmpty()
? DEFAULT_BACKOFF_SECONDS : backoffSeconds;
int index = Math.max(0, Math.min(retryCount - 1, values.size() - 1));
return values.get(index);
}
}
@@ -96,6 +96,10 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
result.setModerationForwardTargets(forwardConfig.getTargets());
result.setModerationForwardOrder(forwardConfig.getOrder());
result.setModerationForwardSecretConfigured(StringUtils.hasText(forwardConfig.getSecret()));
result.setModerationForwardMaxRetry(forwardConfig.getMaxRetry());
result.setModerationForwardBackoffSeconds(forwardConfig.getBackoffSeconds() == null
? ModerationForwardConfig.DEFAULT_BACKOFF_SECONDS
: forwardConfig.getBackoffSeconds());
result.setUpdatedAt(latestUpdateTime());
return result;
@@ -219,11 +223,16 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
}
}
int maxRetry = resolveForwardMaxRetry(dto.getModerationForwardMaxRetry());
List<Long> backoffSeconds = resolveForwardBackoff(dto.getModerationForwardBackoffSeconds());
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("enabled", enabled);
payload.put("targets", orderedTargets);
payload.put("order", order);
payload.put("secret", secret);
payload.put("maxRetry", maxRetry);
payload.put("backoffSeconds", backoffSeconds);
try {
writeValue(MODERATION_FORWARD, "CONFIG", objectMapper.writeValueAsString(payload), true, currentUser.getId());
} catch (JsonProcessingException exception) {
@@ -255,7 +264,20 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
if (StringUtils.hasText(item.asText(""))) order.add(item.asText(""));
});
}
return new ModerationForwardConfig(enabled, targets, node.path("secret").asText(""), order);
int maxRetry = node.path("maxRetry").asInt(ModerationForwardConfig.DEFAULT_MAX_RETRY);
if (maxRetry < 1 || maxRetry > 10) maxRetry = ModerationForwardConfig.DEFAULT_MAX_RETRY;
List<Long> parsedBackoff = new ArrayList<>();
JsonNode backoffNode = node.path("backoffSeconds");
if (backoffNode.isArray()) {
backoffNode.forEach(item -> {
long seconds = item.asLong(0L);
if (seconds > 0) parsedBackoff.add(seconds);
});
}
List<Long> backoffSeconds = parsedBackoff.isEmpty()
? ModerationForwardConfig.DEFAULT_BACKOFF_SECONDS : parsedBackoff;
return new ModerationForwardConfig(enabled, targets, node.path("secret").asText(""), order,
maxRetry, backoffSeconds);
} catch (JsonProcessingException exception) {
log.warn("跨环境转发配置解析失败,按未启用处理");
return ModerationForwardConfig.disabled();
@@ -488,6 +510,32 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
return result;
}
/**
* 归一化最大重试次数:未填写回退默认值,允许范围 1-10。
*/
private int resolveForwardMaxRetry(Integer raw) {
if (raw == null) return ModerationForwardConfig.DEFAULT_MAX_RETRY;
if (raw < 1 || raw > 10) {
throw new IllegalArgumentException("跨环境回调最大重试次数需要在 1-10 之间");
}
return raw;
}
/**
* 归一化退避秒数:未填写回退默认梯度,至少 1 个且每个值需在 1 秒-1 天之间。
*/
private List<Long> resolveForwardBackoff(List<Integer> raw) {
if (raw == null || raw.isEmpty()) return ModerationForwardConfig.DEFAULT_BACKOFF_SECONDS;
List<Long> result = new ArrayList<>();
for (Integer seconds : raw) {
if (seconds == null || seconds < 1 || seconds > 86400) {
throw new IllegalArgumentException("跨环境回调退避秒数需要为 1-86400 秒");
}
result.add(seconds.longValue());
}
return result;
}
/**
* 只允许指向内容审核回调路径:HTTPS 放行(各环境对外地址通常为 HTTPS 域名),
* HTTP 仅允许私网/本机主机,避免被配置为任意公网地址造成 SSRF。
@@ -13,6 +13,10 @@ public class ModerationForwardRecordVO {
private String status;
private Integer retryCount;
private String lastError;
/** 解密后的原始回调报文,仅平台管理员可查,用于 DEAD 任务人工排查。 */
private String payload;
private LocalDateTime nextAttemptAt;
private LocalDateTime finishedAt;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -29,6 +29,8 @@ public class SecureIntegrationConfigVO {
private Map<String, String> moderationForwardTargets;
private List<String> moderationForwardOrder;
private Boolean moderationForwardSecretConfigured;
private Integer moderationForwardMaxRetry;
private List<Long> moderationForwardBackoffSeconds;
private List<ModerationForwardRecordVO> moderationForwardRecent;
private Boolean encryptionKeyConfigured;
@@ -0,0 +1,12 @@
ALTER TABLE t_moderation_callback_forward
MODIFY COLUMN status VARCHAR(16) NOT NULL COMMENT 'PENDING/PROCESSING/SUCCESS/NO_ENV/FAILED/DEAD',
ADD COLUMN next_attempt_at DATETIME NULL COMMENT '下次补偿执行时间',
ADD COLUMN locked_by VARCHAR(100) NULL COMMENT '处理实例与锁标识',
ADD COLUMN locked_at DATETIME NULL COMMENT '最近抢锁时间',
ADD COLUMN finished_at DATETIME NULL COMMENT '终态完成时间',
ADD KEY idx_moderation_callback_forward_due (status, next_attempt_at);
UPDATE t_moderation_callback_forward
SET next_attempt_at = updated_at
WHERE status IN ('PENDING', 'RETRY', 'NO_ENV', 'FAILED', 'TARGET_MISSING')
AND next_attempt_at IS NULL;
@@ -7,10 +7,12 @@ import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerati
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto;
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig;
import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService;
import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService;
import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@@ -19,8 +21,10 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@@ -67,46 +71,16 @@ class WechatContentModerationCallbackControllerTest {
}
@Test
void localHitDoesNotProbeAndForward() throws Exception {
void callbackPersistsBeforeReturningSuccess() throws Exception {
SecureIntegrationConfigService secureConfig = readyWechatConfig();
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
ContentModerationService moderationService = mock(ContentModerationService.class);
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true);
String decoded = "{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"}}";
when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id")).thenReturn(decoded);
when(forwardService.reserveTrace("task-json")).thenReturn(true);
when(moderationService.handleWechatImageResult("task-json", "pass", "微信异步图片审核回调")).thenReturn(true);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
mock(IntegrationProbeService.class), forwardService)).build();
mvc.perform(post("/integration/wechat/content-moderation/callback")
.param("timestamp", "1000")
.param("nonce", "nonce")
.param("msg_signature", "message-signature")
.param("encrypt_type", "aes")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"Encrypt\":\"encrypted-json\"}"))
.andExpect(status().isOk())
.andExpect(content().string("success"));
verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调");
verify(forwardService, never()).probeAndForward(anyString(), anyString(), anyString());
}
@Test
void probeHitSkipsModerationAndForwarding() throws Exception {
SecureIntegrationConfigService secureConfig = readyWechatConfig();
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
IntegrationProbeService probeService = mock(IntegrationProbeService.class);
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true);
when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id"))
.thenReturn("{\"trace_id\":\"probe-1\",\"suggest\":\"review\"}");
when(forwardService.reserveTrace("probe-1")).thenReturn(true);
when(probeService.handleImageCallback("probe-1", "review", null)).thenReturn(true);
when(forwardService.persistCallback(decoded)).thenReturn(42L);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto,
mock(ContentModerationService.class), probeService, forwardService)).build();
mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build();
mvc.perform(post("/integration/wechat/content-moderation/callback")
.param("timestamp", "1000")
@@ -118,23 +92,23 @@ class WechatContentModerationCallbackControllerTest {
.andExpect(status().isOk())
.andExpect(content().string("success"));
verify(forwardService, never()).probeAndForward(anyString(), anyString(), anyString());
InOrder order = inOrder(forwardService);
order.verify(forwardService).persistCallback(decoded);
order.verify(forwardService).submit(42L);
}
@Test
void localMissForwardsRawDecryptedPayload() throws Exception {
void callbackReturnsNon200WhenPersistFails() throws Exception {
SecureIntegrationConfigService secureConfig = readyWechatConfig();
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
ContentModerationService moderationService = mock(ContentModerationService.class);
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);
String decoded = "{\"trace_id\":\"task-prod\",\"result\":{\"suggest\":\"review\"},\"errmsg\":\"人工复核\"}";
when(crypto.decrypt(anyString(), anyString(), anyString())).thenReturn(decoded);
when(forwardService.reserveTrace("task-prod")).thenReturn(true);
when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString())).thenReturn(false);
when(forwardService.probeAndForward(anyString(), anyString(), anyString())).thenReturn(true);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
mock(IntegrationProbeService.class), forwardService)).build();
when(crypto.decrypt(anyString(), anyString(), anyString()))
.thenReturn("{\"trace_id\":\"task-persist-fail\"}");
when(forwardService.persistCallback(anyString()))
.thenThrow(new IllegalStateException("数据库不可用"));
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto,
mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build();
mvc.perform(post("/integration/wechat/content-moderation/callback")
.param("timestamp", "1000")
@@ -143,57 +117,54 @@ class WechatContentModerationCallbackControllerTest {
.param("encrypt_type", "aes")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"Encrypt\":\"encrypted-json\"}"))
.andExpect(status().isOk())
.andExpect(content().string("success"));
.andExpect(status().isInternalServerError())
.andExpect(content().string("persist_failed"));
verify(forwardService).probeAndForward(eq("task-prod"), eq(decoded), anyString());
verify(forwardService, never()).releaseTrace("task-prod");
verify(forwardService, never()).submit(any());
verify(forwardService, never()).reserveTrace(anyString());
}
@Test
void duplicateTraceReturnsSuccessWithoutProcessing() throws Exception {
void duplicateCallbackReusesTaskAndStillReturnsSuccess() throws Exception {
SecureIntegrationConfigService secureConfig = readyWechatConfig();
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
ContentModerationService moderationService = mock(ContentModerationService.class);
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);
when(crypto.decrypt(anyString(), anyString(), anyString()))
.thenReturn("{\"trace_id\":\"task-dup\",\"suggest\":\"review\"}");
when(forwardService.reserveTrace("task-dup")).thenReturn(false);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
mock(IntegrationProbeService.class), forwardService)).build();
when(forwardService.persistCallback(anyString())).thenReturn(7L);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto,
mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build();
mvc.perform(post("/integration/wechat/content-moderation/callback")
.param("timestamp", "1000")
.param("nonce", "nonce")
.param("msg_signature", "message-signature")
.param("encrypt_type", "aes")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"Encrypt\":\"encrypted-json\"}"))
.andExpect(status().isOk())
.andExpect(content().string("success"));
for (int attempt = 0; attempt < 2; attempt++) {
mvc.perform(post("/integration/wechat/content-moderation/callback")
.param("timestamp", "1000")
.param("nonce", "nonce")
.param("msg_signature", "message-signature")
.param("encrypt_type", "aes")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"Encrypt\":\"encrypted-json\"}"))
.andExpect(status().isOk())
.andExpect(content().string("success"));
}
verify(moderationService, never()).handleWechatImageResult(anyString(), anyString(), anyString());
verify(forwardService, never()).probeAndForward(anyString(), anyString(), anyString());
verify(forwardService, times(2)).persistCallback(anyString());
verify(forwardService, times(2)).submit(7L);
}
@Test
void keepsXmlEnvelopeSupportForAesEncryptedCallback() throws Exception {
SecureIntegrationConfigService secureConfig = readyWechatConfig();
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
ContentModerationService moderationService = mock(ContentModerationService.class);
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
String xml = "<xml><Encrypt>encrypted-xml</Encrypt></xml>";
when(crypto.encryptedValue(xml)).thenReturn("encrypted-xml");
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature")).thenReturn(true);
String decodedXml = "<xml><trace_id>task-xml</trace_id><suggest>review</suggest></xml>";
when(crypto.decrypt("encrypted-xml", "encoding-aes-key", "mini-app-id")).thenReturn(decodedXml);
when(crypto.value(decodedXml, "trace_id")).thenReturn("task-xml");
when(crypto.value(decodedXml, "suggest")).thenReturn("review");
when(forwardService.reserveTrace("task-xml")).thenReturn(true);
when(moderationService.handleWechatImageResult("task-xml", "review", "微信异步图片审核回调")).thenReturn(true);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
mock(IntegrationProbeService.class), forwardService)).build();
when(forwardService.persistCallback(decodedXml)).thenReturn(11L);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto,
mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build();
mvc.perform(post("/integration/wechat/content-moderation/callback")
.param("timestamp", "1000")
@@ -205,7 +176,8 @@ class WechatContentModerationCallbackControllerTest {
.andExpect(status().isOk())
.andExpect(content().string("success"));
verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调");
verify(forwardService).persistCallback(decodedXml);
verify(forwardService).submit(11L);
}
@Test
@@ -228,6 +200,8 @@ class WechatContentModerationCallbackControllerTest {
.content("{\"trace_id\":\"task-claim\",\"suggest\":\"review\"}"))
.andExpect(status().isOk())
.andExpect(content().string("CLAIMED"));
verify(forwardService, never()).submit(any());
}
@Test
@@ -284,7 +258,7 @@ class WechatContentModerationCallbackControllerTest {
assertThrows(IllegalArgumentException.class, () -> controller.callback(null, null, null, null, null,
"prod", "2", "1000", "forward-nonce", "forward-signature",
"{\"trace_id\":\"loop-task\"}"));
"{\"trace_id\":\"loop-task\"}", new MockHttpServletResponse()));
}
@Test
@@ -297,7 +271,7 @@ class WechatContentModerationCallbackControllerTest {
assertThrows(IllegalArgumentException.class, () -> controller.callback(null, null, null, null, null,
"sit", "1", "1000", "forward-nonce", "forward-signature",
"{\"trace_id\":\"self-task\"}"));
"{\"trace_id\":\"self-task\"}", new MockHttpServletResponse()));
}
@Test
@@ -310,7 +284,7 @@ class WechatContentModerationCallbackControllerTest {
assertThrows(IllegalArgumentException.class, () -> controller.callback(null, null, null, null, null,
"prod", "1", "1000", "forward-nonce", "bad-signature",
"{\"trace_id\":\"task-1\"}"));
"{\"trace_id\":\"task-1\"}", new MockHttpServletResponse()));
}
private SecureIntegrationConfigService readyWechatConfig() {
@@ -1,16 +1,26 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationForwardHttpClient;
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationProbeResult;
import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto;
import com.xiaowang.jayucloud.salon.core.modules.system.entity.ModerationCallbackForwardDO;
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.ModerationCallbackForwardMapper;
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig;
import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService;
import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
@@ -18,19 +28,26 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -44,6 +61,8 @@ class ContentModerationForwardServiceImplTest {
private RedisTemplate<String, Object> redisTemplate;
private ValueOperations<String, Object> valueOperations;
private ModerationForwardHttpClient forwardHttpClient;
private IntegrationProbeService probeService;
private ContentModerationService moderationService;
private ContentModerationForwardServiceImpl service;
@BeforeEach
@@ -53,121 +72,198 @@ class ContentModerationForwardServiceImplTest {
redisTemplate = mock(RedisTemplate.class);
valueOperations = mock(ValueOperations.class);
forwardHttpClient = mock(ModerationForwardHttpClient.class);
probeService = mock(IntegrationProbeService.class);
moderationService = mock(ContentModerationService.class);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(true);
SalonDeployProperties deployProperties = new SalonDeployProperties();
deployProperties.setEnv("sit");
service = new ContentModerationForwardServiceImpl(forwardMapper, secureIntegrationConfigService,
deployProperties, redisTemplate, forwardHttpClient);
deployProperties, redisTemplate, forwardHttpClient, probeService, moderationService,
new ObjectMapper(), mock(WechatCallbackCrypto.class));
}
// ---------- 接收侧:先落库 ----------
@Test
void localHitDoesNotForward() {
// 本地命中由控制器直接结束,这里只覆盖服务侧探测顺序的起点:第一个目标即 CLAIMED。
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev", "prod")));
when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED);
void persistCallbackInsertsPendingTaskWithDecodedPayload() {
doAnswer(invocation -> {
ModerationCallbackForwardDO row = invocation.getArgument(0);
row.setId(101L);
return 1;
}).when(forwardMapper).insert(any(ModerationCallbackForwardDO.class));
assertTrue(service.probeAndForward("trace-1", "{\"trace_id\":\"trace-1\"}", "audit"));
Long taskId = service.persistCallback("{\"trace_id\":\"trace-1\",\"result\":{\"suggest\":\"review\"}}");
verify(forwardHttpClient, never()).probe(eq(PROD_TARGET), anyString(), any());
assertEquals(101L, taskId);
ModerationCallbackForwardDO row = capturedInsert();
assertEquals("CLAIMED", row.getStatus());
assertEquals("dev", row.getTargetEnv());
assertEquals("trace-1", row.getTraceId());
assertEquals("sit", row.getSourceEnv());
assertEquals("PENDING", row.getStatus());
assertEquals(0, row.getRetryCount());
assertNotNull(row.getNextAttemptAt());
assertEquals("{\"trace_id\":\"trace-1\",\"result\":{\"suggest\":\"review\"}}", row.getPayload());
}
@Test
void notMineContinuesToNextTargetAndStopsOnClaimed() {
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev", "prod")));
void persistCallbackReturnsExistingTaskForDuplicateTrace() {
ModerationCallbackForwardDO existing = row(9L, "trace-dup", "SUCCESS", 0);
when(forwardMapper.selectOne(any())).thenReturn(existing);
assertEquals(9L, service.persistCallback("{\"trace_id\":\"trace-dup\"}"));
verify(forwardMapper, never()).insert(any(ModerationCallbackForwardDO.class));
}
@Test
void persistCallbackRecoversWhenConcurrentInsertHitsDuplicateKey() {
ModerationCallbackForwardDO existing = row(9L, "trace-race", "PENDING", 0);
when(forwardMapper.selectOne(any())).thenReturn(null, existing);
when(forwardMapper.insert(any(ModerationCallbackForwardDO.class)))
.thenThrow(new DuplicateKeyException("duplicate trace"));
assertEquals(9L, service.persistCallback("{\"trace_id\":\"trace-race\"}"));
verify(forwardMapper, times(1)).insert(any(ModerationCallbackForwardDO.class));
}
@Test
void persistCallbackStoresUntracedPayloadAsDead() {
doAnswer(invocation -> {
ModerationCallbackForwardDO row = invocation.getArgument(0);
row.setId(102L);
return 1;
}).when(forwardMapper).insert(any(ModerationCallbackForwardDO.class));
assertEquals(102L, service.persistCallback("{\"result\":{\"suggest\":\"review\"}}"));
ModerationCallbackForwardDO row = capturedInsert();
assertTrue(row.getTraceId().startsWith("untraced-"));
assertEquals("DEAD", row.getStatus());
assertNotNull(row.getLastError());
assertNull(row.getNextAttemptAt());
assertNotNull(row.getFinishedAt());
}
// ---------- 异步执行与状态机 ----------
@Test
void executeTaskProcessesLocalHitAndMarksSuccess() {
ModerationCallbackForwardDO row = row(1L, "trace-local", "PENDING", 0);
when(forwardMapper.selectById(1L)).thenReturn(row);
when(forwardMapper.update(isNull(), any())).thenReturn(1);
when(probeService.handleImageCallback(eq("trace-local"), eq("review"), isNull())).thenReturn(true);
service.executeTask(1L);
UpdateWrapper<ModerationCallbackForwardDO> outcome = outcomeWrapper();
assertTrue(outcome.getParamNameValuePairs().containsValue("SUCCESS"));
assertTrue(outcome.getParamNameValuePairs().containsValue("sit"));
verify(forwardHttpClient, never()).probe(anyString(), anyString(), any());
}
@Test
void executeTaskForwardsInOrderAndStopsOnClaimed() {
ModerationCallbackForwardDO row = row(2L, "trace-forward", "PENDING", 0);
when(forwardMapper.selectById(2L)).thenReturn(row);
when(forwardMapper.update(isNull(), any())).thenReturn(1);
when(secureIntegrationConfigService.getModerationForwardConfig())
.thenReturn(config(Arrays.asList("dev", "prod")));
when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.NOT_MINE);
when(forwardHttpClient.probe(eq(PROD_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED);
assertTrue(service.probeAndForward("trace-2", "{\"trace_id\":\"trace-2\"}", "audit"));
service.executeTask(2L);
InOrder order = inOrder(forwardHttpClient);
order.verify(forwardHttpClient).probe(eq(DEV_TARGET), anyString(), any());
order.verify(forwardHttpClient).probe(eq(PROD_TARGET), anyString(), any());
ModerationCallbackForwardDO row = capturedInsert();
assertEquals("CLAIMED", row.getStatus());
assertEquals("prod", row.getTargetEnv());
UpdateWrapper<ModerationCallbackForwardDO> outcome = outcomeWrapper();
assertTrue(outcome.getParamNameValuePairs().containsValue("SUCCESS"));
assertTrue(outcome.getParamNameValuePairs().containsValue("prod"));
}
@Test
void errorContinuesToNextTargetAndRecordsAlertNote() {
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev", "prod")));
when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.ERROR);
when(forwardHttpClient.probe(eq(PROD_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED);
void executeTaskRecordsNoEnvAndSchedulesBackoff() {
ModerationCallbackForwardDO row = row(3L, "trace-no-env", "PENDING", 0);
when(forwardMapper.selectById(3L)).thenReturn(row);
when(forwardMapper.update(isNull(), any())).thenReturn(1);
when(secureIntegrationConfigService.getModerationForwardConfig())
.thenReturn(ModerationForwardConfig.disabled());
assertTrue(service.probeAndForward("trace-3", "{\"trace_id\":\"trace-3\"}", "audit"));
service.executeTask(3L);
InOrder order = inOrder(forwardHttpClient);
order.verify(forwardHttpClient).probe(eq(DEV_TARGET), anyString(), any());
order.verify(forwardHttpClient).probe(eq(PROD_TARGET), anyString(), any());
ModerationCallbackForwardDO row = capturedInsert();
assertEquals("CLAIMED", row.getStatus());
assertEquals("prod", row.getTargetEnv());
assertTrue(row.getLastError().contains("dev"));
UpdateWrapper<ModerationCallbackForwardDO> outcome = outcomeWrapper();
assertTrue(outcome.getParamNameValuePairs().containsValue("NO_ENV"));
assertTrue(outcome.getParamNameValuePairs().containsValue(1));
assertTrue(hasFutureAttempt(outcome, 25), "首次补偿应至少等待默认 30 秒");
verify(redisTemplate).delete("salon:content-moderation:claim:trace-no-env");
}
@Test
void claimedStopsRemainingTargets() {
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev", "prod")));
when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED);
void executeTaskMarksDeadAndAlertsWhenRetryLimitExceeded() {
ModerationCallbackForwardDO row = row(4L, "trace-dead", "FAILED", 4);
when(forwardMapper.selectById(4L)).thenReturn(row);
when(forwardMapper.update(isNull(), any())).thenReturn(1);
when(secureIntegrationConfigService.getModerationForwardConfig())
.thenReturn(ModerationForwardConfig.disabled());
List<String> logs = attachLogAppender();
assertTrue(service.probeAndForward("trace-4", "{\"trace_id\":\"trace-4\"}", "audit"));
service.executeTask(4L);
verify(forwardHttpClient, never()).probe(eq(PROD_TARGET), anyString(), any());
UpdateWrapper<ModerationCallbackForwardDO> outcome = outcomeWrapper();
assertTrue(outcome.getParamNameValuePairs().containsValue("DEAD"));
assertTrue(outcome.getParamNameValuePairs().containsValue(5));
assertNull(firstLocalDateTimeIgnoringNull(outcome));
assertTrue(logs.stream().anyMatch(message -> message.contains("MODERATION_CALLBACK_DEAD")),
"达到最大重试后必须输出告警日志");
}
@Test
void allTargetsNotMineRecordsNoEnv() {
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev", "prod")));
when(forwardHttpClient.probe(anyString(), anyString(), any())).thenReturn(ModerationProbeResult.NOT_MINE);
void executeTaskShortCircuitsWhenTraceAlreadyReserved() {
ModerationCallbackForwardDO row = row(5L, "trace-idempotent", "PENDING", 0);
when(forwardMapper.selectById(5L)).thenReturn(row);
when(forwardMapper.update(isNull(), any())).thenReturn(1);
when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(false);
assertFalse(service.probeAndForward("trace-5", "{\"trace_id\":\"trace-5\"}", "audit"));
service.executeTask(5L);
ModerationCallbackForwardDO row = capturedInsert();
assertEquals("NO_ENV", row.getStatus());
assertTrue(row.getLastError().contains("dev"));
assertTrue(row.getLastError().contains("prod"));
assertTrue(row.getLastError().contains("NOT_MINE"));
UpdateWrapper<ModerationCallbackForwardDO> outcome = outcomeWrapper();
assertTrue(outcome.getParamNameValuePairs().containsValue("SUCCESS"));
verify(probeService, never()).handleImageCallback(anyString(), anyString(), any());
verify(moderationService, never()).handleWechatImageResult(anyString(), anyString(), anyString());
}
@Test
void allTargetsErrorRecordsNoEnv() {
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev", "prod")));
when(forwardHttpClient.probe(anyString(), anyString(), any())).thenReturn(ModerationProbeResult.ERROR);
void executeTaskSkipsWhenClaimLosesToAnotherInstance() {
ModerationCallbackForwardDO row = row(6L, "trace-locked", "PENDING", 0);
when(forwardMapper.selectById(6L)).thenReturn(row);
when(forwardMapper.update(isNull(), any())).thenReturn(0);
assertFalse(service.probeAndForward("trace-6", "{\"trace_id\":\"trace-6\"}", "audit"));
service.executeTask(6L);
ModerationCallbackForwardDO row = capturedInsert();
assertEquals("NO_ENV", row.getStatus());
assertTrue(row.getLastError().contains("ERROR"));
verify(forwardMapper, times(1)).selectById(6L);
verify(probeService, never()).handleImageCallback(anyString(), anyString(), any());
verify(moderationService, never()).handleWechatImageResult(anyString(), anyString(), anyString());
}
@Test
void disabledConfigRecordsNoEnvWithoutProbing() {
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(ModerationForwardConfig.disabled());
void recoverPendingTasksDispatchesUnfinishedRecords() {
ModerationCallbackForwardDO first = row(7L, "trace-r1", "PENDING", 0);
ModerationCallbackForwardDO second = row(8L, "trace-r2", "FAILED", 2);
when(forwardMapper.selectList(any())).thenReturn(Arrays.asList(first, second));
assertFalse(service.probeAndForward("trace-7", "{\"trace_id\":\"trace-7\"}", "audit"));
verify(forwardHttpClient, never()).probe(anyString(), anyString(), any());
ModerationCallbackForwardDO row = capturedInsert();
assertEquals("NO_ENV", row.getStatus());
assertEquals(2, service.recoverPendingTasks());
}
@Test
void configuredTargetsExcludeLocalEnvAndKeepConfiguredOrder() {
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("prod", "dev")));
when(forwardHttpClient.probe(eq(PROD_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.NOT_MINE);
when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED);
void retryDueTasksDispatchesDueRecords() {
when(forwardMapper.selectList(any())).thenReturn(Collections.singletonList(row(9L, "trace-due", "NO_ENV", 1)));
assertTrue(service.probeAndForward("trace-8", "{\"trace_id\":\"trace-8\"}", "audit"));
InOrder order = inOrder(forwardHttpClient);
order.verify(forwardHttpClient).probe(eq(PROD_TARGET), anyString(), any());
order.verify(forwardHttpClient).probe(eq(DEV_TARGET), anyString(), any());
assertEquals(1, service.retryDueTasks());
}
// ---------- Redis 幂等占位 ----------
@Test
void reserveTraceReturnsFalseForDuplicate() {
when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(false);
@@ -190,24 +286,7 @@ class ContentModerationForwardServiceImplTest {
verify(redisTemplate).delete("salon:content-moderation:claim:trace-release");
}
@Test
void existingRecordIsUpdatedInsteadOfInserted() {
ModerationCallbackForwardDO existing = new ModerationCallbackForwardDO();
existing.setId(9L);
existing.setTraceId("trace-existing");
existing.setStatus("NO_ENV");
existing.setCreatedAt(LocalDateTime.now().minusMinutes(1));
when(forwardMapper.selectOne(any())).thenReturn(existing);
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev")));
when(forwardHttpClient.probe(eq(DEV_TARGET), anyString(), any())).thenReturn(ModerationProbeResult.CLAIMED);
assertTrue(service.probeAndForward("trace-existing", "{\"trace_id\":\"trace-existing\"}", "audit"));
assertEquals("CLAIMED", existing.getStatus());
assertEquals("dev", existing.getTargetEnv());
verify(forwardMapper).updateById(existing);
verify(forwardMapper, never()).insert(any(ModerationCallbackForwardDO.class));
}
// ---------- 转发验签 ----------
@Test
void verifySignatureAcceptsValidRequest() {
@@ -243,7 +322,20 @@ class ContentModerationForwardServiceImplTest {
Map<String, String> targets = new LinkedHashMap<>();
targets.put("dev", DEV_TARGET);
targets.put("prod", PROD_TARGET);
return new ModerationForwardConfig(true, targets, SECRET, order);
return new ModerationForwardConfig(true, targets, SECRET, order,
ModerationForwardConfig.DEFAULT_MAX_RETRY, ModerationForwardConfig.DEFAULT_BACKOFF_SECONDS);
}
private ModerationCallbackForwardDO row(Long id, String traceId, String status, int retryCount) {
ModerationCallbackForwardDO row = new ModerationCallbackForwardDO();
row.setId(id);
row.setTraceId(traceId);
row.setPayload("{\"trace_id\":\"" + traceId + "\",\"result\":{\"suggest\":\"review\"}}");
row.setSourceEnv("sit");
row.setStatus(status);
row.setRetryCount(retryCount);
row.setCreatedAt(LocalDateTime.now().minusMinutes(10));
return row;
}
private ModerationCallbackForwardDO capturedInsert() {
@@ -252,6 +344,46 @@ class ContentModerationForwardServiceImplTest {
return captor.getValue();
}
@SuppressWarnings("unchecked")
private UpdateWrapper<ModerationCallbackForwardDO> outcomeWrapper() {
ArgumentCaptor<UpdateWrapper<ModerationCallbackForwardDO>> captor =
ArgumentCaptor.forClass(UpdateWrapper.class);
verify(forwardMapper, times(2)).update(isNull(), captor.capture());
return captor.getAllValues().get(1);
}
private LocalDateTime firstLocalDateTimeIgnoringNull(UpdateWrapper<ModerationCallbackForwardDO> wrapper) {
LocalDateTime now = LocalDateTime.now();
for (Object value : wrapper.getParamNameValuePairs().values()) {
if (value instanceof LocalDateTime && ((LocalDateTime) value).isAfter(now.plusSeconds(1))) {
return (LocalDateTime) value;
}
}
return null;
}
private boolean hasFutureAttempt(UpdateWrapper<ModerationCallbackForwardDO> wrapper, int minSeconds) {
LocalDateTime threshold = LocalDateTime.now().plusSeconds(minSeconds);
return wrapper.getParamNameValuePairs().values().stream()
.filter(LocalDateTime.class::isInstance)
.map(LocalDateTime.class::cast)
.anyMatch(value -> value.isAfter(threshold));
}
private List<String> attachLogAppender() {
List<String> messages = new CopyOnWriteArrayList<>();
AbstractAppender appender = new AbstractAppender("moderation-test", null, null, false) {
@Override
public void append(LogEvent event) {
messages.add(event.getMessage().getFormattedMessage());
}
};
appender.start();
Logger logger = (Logger) LogManager.getLogger(ContentModerationForwardServiceImpl.class);
logger.addAppender(appender);
return messages;
}
private String sign(String secret, String timestamp, String nonce, String body) {
try {
javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256");
+8 -1
View File
@@ -1598,6 +1598,8 @@ export interface SecureIntegrationConfigVO {
moderationForwardTargets?: Record<string, string>
moderationForwardOrder?: string[]
moderationForwardSecretConfigured?: boolean
moderationForwardMaxRetry?: number
moderationForwardBackoffSeconds?: number[]
moderationForwardRecent?: ModerationForwardRecordVO[]
encryptionKeyConfigured: boolean
updatedAt?: string
@@ -1609,9 +1611,12 @@ export interface ModerationForwardRecordVO {
traceId: string
sourceEnv?: string
targetEnv?: string
status: 'CLAIMED' | 'NO_ENV' | 'PENDING' | 'SUCCESS' | 'RETRY' | 'FAILED' | 'TARGET_MISSING' | string
status: 'CLAIMED' | 'PENDING' | 'PROCESSING' | 'SUCCESS' | 'NO_ENV' | 'FAILED' | 'DEAD' | 'RETRY' | 'TARGET_MISSING' | string
retryCount?: number
lastError?: string
payload?: string
nextAttemptAt?: string
finishedAt?: string
createdAt?: string
updatedAt?: string
}
@@ -1662,6 +1667,8 @@ export interface SecureIntegrationConfigUpdate {
moderationForwardOrder?: string[]
moderationForwardSecret?: string
clearModerationForwardSecret?: boolean
moderationForwardMaxRetry?: number
moderationForwardBackoffSeconds?: number[]
}
/**
@@ -347,11 +347,26 @@
<a-input-number v-model:value="moderationForwardOrder[env.key]" :min="1" :max="3" :precision="0" />
</div>
</article>
<article class="field">
<div class="field__head"><span class="field__label">补偿最大重试次数</span></div>
<p class="field__desc">未认领或处理失败的任务按退避节奏补偿,超过次数置为 DEAD 并告警。</p>
<div class="field__control">
<a-input-number v-model:value="moderationForwardMaxRetry" :min="1" :max="10" :precision="0" />
</div>
</article>
<article class="field">
<div class="field__head"><span class="field__label">退避秒数(第 1-4 次)</span></div>
<p class="field__desc">默认 30 / 120 / 600 / 3600 秒,超出次数后沿用最后一个梯度。</p>
<div class="field__control forward-backoff">
<a-input-number v-for="(_, index) in moderationForwardBackoffSeconds" :key="index"
v-model:value="moderationForwardBackoffSeconds[index]" :min="1" :max="86400" :precision="0" />
</div>
</article>
</div>
<div class="forward-recent">
<div class="forward-recent__head">
<strong>最近转发结果</strong>
<span class="control-note">NO_ENV 表示所有目标环境均未认领,需人工排查;CLAIMED 表示已由目标环境处理。</span>
<strong>最近回调任务</strong>
<span class="control-note">接收即落库并立即应答微信;PENDING / PROCESSING 表示异步处理中,NO_ENV / FAILED 进入补偿,DEAD 需人工排查原始报文。</span>
</div>
<div v-if="!(secureStatus?.moderationForwardRecent || []).length" class="control-note">暂无转发记录</div>
<ul v-else class="forward-recent__list">
@@ -360,7 +375,12 @@
<span class="forward-recent__env">{{ item.sourceEnv || '-' }} → {{ item.targetEnv || '-' }}</span>
<span class="forward-recent__trace" :title="item.traceId">{{ item.traceId }}</span>
<span class="forward-recent__time">{{ formatProbeTime(item.createdAt) }}</span>
<span v-if="item.nextAttemptAt" class="forward-recent__time">下次补偿 {{ formatProbeTime(item.nextAttemptAt) }}</span>
<span v-if="item.lastError" class="forward-recent__error">{{ item.lastError }}</span>
<details v-if="item.payload" class="forward-recent__payload">
<summary>原始报文</summary>
<pre>{{ item.payload }}</pre>
</details>
</li>
</ul>
</div>
@@ -536,6 +556,8 @@ const moderationForwardEnabled = ref(false)
const moderationForwardTargets = reactive<Record<'dev' | 'sit' | 'prod', string>>({ dev: '', sit: '', prod: '' })
const moderationForwardOrder = reactive<Record<'dev' | 'sit' | 'prod', number>>({ dev: 1, sit: 2, prod: 3 })
const moderationForwardSecret = ref('')
const moderationForwardMaxRetry = ref(4)
const moderationForwardBackoffSeconds = reactive<number[]>([30, 120, 600, 3600])
const clearModerationForwardSecret = ref(false)
const savingModerationForward = ref(false)
const forwardEnvTargets = [
@@ -710,6 +732,11 @@ const load = async () => {
moderationForwardOrder[env.key] = position >= 0 ? position + 1 : index + 1
})
moderationForwardSecret.value = ''
moderationForwardMaxRetry.value = secureConfig.moderationForwardMaxRetry ?? 4
const loadedBackoff = secureConfig.moderationForwardBackoffSeconds || [30, 120, 600, 3600]
moderationForwardBackoffSeconds.forEach((_, index) => {
moderationForwardBackoffSeconds[index] = loadedBackoff[index] ?? loadedBackoff[loadedBackoff.length - 1] ?? 3600
})
clearModerationForwardSecret.value = false
mapSecrets.tencentWeb = ''
mapSecrets.amapWeb = ''
@@ -1037,8 +1064,15 @@ const saveModerationConfig = async () => {
}
const forwardStatusLabel = (status?: string) => ({
CLAIMED: '已认领', NO_ENV: '无环境认领',
PENDING: '待转发', SUCCESS: '已转发', RETRY: '待重试', FAILED: '失败', TARGET_MISSING: '目标未配置'
CLAIMED: '已认领',
PENDING: '待处理',
PROCESSING: '处理中',
SUCCESS: '已处理',
NO_ENV: '无环境认领',
FAILED: '失败待重试',
DEAD: '已终止',
RETRY: '待重试',
TARGET_MISSING: '目标未配置'
} as Record<string, string>)[status || ''] || '未知'
const saveModerationForwardConfig = async () => {
@@ -1067,7 +1101,9 @@ const saveModerationForwardConfig = async () => {
.sort((a, b) => moderationForwardOrder[a.key] - moderationForwardOrder[b.key])
.map(env => env.key),
moderationForwardSecret: moderationForwardSecret.value,
clearModerationForwardSecret: clearModerationForwardSecret.value
clearModerationForwardSecret: clearModerationForwardSecret.value,
moderationForwardMaxRetry: moderationForwardMaxRetry.value,
moderationForwardBackoffSeconds: [...moderationForwardBackoffSeconds]
})
moderationForwardSecret.value = ''
clearModerationForwardSecret.value = false
@@ -1349,6 +1385,14 @@ onMounted(() => {
}
.forward-recent__time { color: var(--text-color-secondary, #6b7280); }
.forward-recent__error { color: var(--danger-color, #c0392b); }
.forward-recent__payload { flex: 1 1 100%; }
.forward-recent__payload summary { cursor: pointer; color: var(--text-color-secondary, #6b7280); }
.forward-recent__payload pre {
margin: 4px 0 0;
font-size: 12px;
white-space: pre-wrap;
word-break: break-all;
}
@media (max-width: 760px) {
.settings-subsection__head { flex-direction: column; align-items: stretch; }
}