Merge pull request '微信审核回调改为先落库后应答并异步探测补偿' (#103) from dev into sit
自动发布测试环境 Nacos 配置 / publish (push) Successful in 30s
自动发布测试环境 Nacos 配置 / publish (push) Successful in 30s
Reviewed-on: http://wcsrv.top:3000/xiaowang/JayuCloud/pulls/103
This commit was merged in pull request #103.
This commit is contained in:
+14
@@ -0,0 +1,14 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.artist.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 美甲师专属颜色更新请求。
|
||||
*/
|
||||
@Data
|
||||
public class ArtistColorUpdateDTO {
|
||||
/**
|
||||
* 十六进制颜色值,格式 #RRGGBB;空值表示恢复默认色。
|
||||
*/
|
||||
private String color;
|
||||
}
|
||||
+8
@@ -48,6 +48,14 @@ public interface NailArtistInfoService extends IService<NailArtistInfoDO> {
|
||||
/** 保存运营字段,并将美甲师对外展示资料提交审核。 */
|
||||
NailArtistInfoDTO submitNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO, Long authorUserId);
|
||||
|
||||
/**
|
||||
* 更新美甲师在日程规划中使用的专属颜色。
|
||||
* @param userId 美甲师用户ID
|
||||
* @param color 颜色值,空值表示恢复默认色
|
||||
* @return 更新后的美甲师信息
|
||||
*/
|
||||
NailArtistInfoDTO updateArtistColor(Long userId, String color);
|
||||
|
||||
/**
|
||||
* 获取所有可用的美甲师信息(前台使用)
|
||||
* @return 美甲师信息列表
|
||||
|
||||
+46
@@ -24,6 +24,7 @@ import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.common.BusinessException;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.artist.service.NailArtistInfoService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
@@ -256,6 +257,51 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
return saveNailArtistInfo(dto, authorUserId, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
@org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
|
||||
public NailArtistInfoDTO updateArtistColor(Long userId, String color) {
|
||||
if (userId == null || userId <= 0) {
|
||||
throw new BusinessException(400, "美甲师用户ID不能为空");
|
||||
}
|
||||
UserDO user = userMapper.selectById(userId);
|
||||
if (user == null || isDeleted(user.getIsDelete())) {
|
||||
throw new BusinessException(404, "美甲师信息不存在");
|
||||
}
|
||||
if (!Integer.valueOf(3).equals(user.getType())) {
|
||||
throw new BusinessException(400, "仅支持修改美甲师专属颜色");
|
||||
}
|
||||
String normalizedColor = normalizeArtistColor(color);
|
||||
NailArtistInfoDO entity = getOne(new LambdaQueryWrapper<NailArtistInfoDO>()
|
||||
.eq(NailArtistInfoDO::getUserId, userId)
|
||||
.eq(NailArtistInfoDO::getIsDelete, 0)
|
||||
.last("LIMIT 1"));
|
||||
if (entity == null) {
|
||||
entity = new NailArtistInfoDO();
|
||||
entity.setUserId(userId);
|
||||
entity.setIdentity("");
|
||||
entity.setExperience(0);
|
||||
entity.setSkills("");
|
||||
entity.setPortfolio("");
|
||||
entity.setStatus(1);
|
||||
entity.setParticipateProduction(1);
|
||||
entity.setModerationStatus("APPROVED");
|
||||
}
|
||||
entity.setColor(normalizedColor);
|
||||
saveOrUpdate(entity);
|
||||
return convertToDTO(entity);
|
||||
}
|
||||
|
||||
private String normalizeArtistColor(String color) {
|
||||
if (!StringUtils.hasText(color)) {
|
||||
return null;
|
||||
}
|
||||
String value = color.trim().toUpperCase(java.util.Locale.ROOT);
|
||||
if (!value.matches("#[0-9A-F]{6}")) {
|
||||
throw new BusinessException(400, "美甲师专属颜色格式不正确,应为 #RRGGBB");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private NailArtistInfoDTO saveNailArtistInfo(NailArtistInfoDTO dto, Long authorUserId, boolean moderatePublicProfile) {
|
||||
if (dto == null || dto.getUserId() == null) {
|
||||
throw new IllegalArgumentException("美甲师用户信息不能为空");
|
||||
|
||||
+14
@@ -4,6 +4,7 @@ import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.artist.dto.ArtistColorUpdateDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.artist.dto.ArtistScheduleDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.artist.dto.ArtistScheduleExceptionDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.artist.dto.ArtistScheduleRuleDTO;
|
||||
@@ -263,6 +264,19 @@ public class AdminManagerController {
|
||||
return Result.success(nailArtistInfoService.submitNailArtistInfo(dto, currentUser.getId()));
|
||||
}
|
||||
|
||||
@PutMapping("/employees/{userId}/color")
|
||||
@RequirePermission("nail_artist:edit")
|
||||
@OperationGuard(action = "manager-nail-artist-color", ttlSeconds = 10, message = "美甲师颜色保存处理中,请勿重复提交")
|
||||
public Result<NailArtistInfoDTO> updateEmployeeColor(HttpServletRequest request,
|
||||
@PathVariable Long userId,
|
||||
@RequestBody(required = false) ArtistColorUpdateDTO dto) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权编辑其他店铺员工");
|
||||
}
|
||||
return Result.success(nailArtistInfoService.updateArtistColor(userId, dto == null ? null : dto.getColor()));
|
||||
}
|
||||
|
||||
@PostMapping("/employees/users")
|
||||
@RequirePermission("user:create")
|
||||
@OperationGuard(action = "manager-user-create", ttlSeconds = 10, message = "员工账号创建处理中,请勿重复提交")
|
||||
|
||||
+79
-124
@@ -2,13 +2,11 @@ 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;
|
||||
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.ModerationForwardConfig;
|
||||
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;
|
||||
@@ -32,8 +30,8 @@ import java.util.Locale;
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/integration/wechat/content-moderation")
|
||||
public class WechatContentModerationCallbackController {
|
||||
private static final String FORWARD_BY_HEADER = "X-Moderation-Forward-By";
|
||||
private static final String FORWARD_HOP_HEADER = "X-Moderation-Forward-Hop";
|
||||
private static final String CLAIMED = "CLAIMED";
|
||||
private static final String NOT_MINE = "NOT_MINE";
|
||||
|
||||
private final SecureIntegrationConfigService secureIntegrationConfigService;
|
||||
private final WechatMiniProperties wechatProperties;
|
||||
@@ -80,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);
|
||||
}
|
||||
@@ -98,130 +97,103 @@ public class WechatContentModerationCallbackController {
|
||||
throw new IllegalArgumentException("微信审核回调仅接受 AES 加密消息");
|
||||
}
|
||||
String decoded = crypto.decrypt(encrypted, config.getEncodingAesKey(), wechatProperties.getAppId());
|
||||
String taskId;
|
||||
String suggest;
|
||||
String reason;
|
||||
String extra;
|
||||
if (decoded.trim().startsWith("<")) {
|
||||
taskId = firstNonBlank(crypto.value(decoded, "trace_id"), crypto.value(decoded, "TraceId"), crypto.value(decoded, "task_id"));
|
||||
suggest = firstNonBlank(crypto.value(decoded, "suggest"), crypto.value(decoded, "Suggest"), "review");
|
||||
reason = firstNonBlank(crypto.value(decoded, "errmsg"), crypto.value(decoded, "label"), "微信异步图片审核回调");
|
||||
extra = firstNonBlank(crypto.value(decoded, "extra"), crypto.value(decoded, "Extra"));
|
||||
} else {
|
||||
JsonNode root = objectMapper.readTree(decoded);
|
||||
taskId = firstText(root, "trace_id", "traceId", "task_id");
|
||||
suggest = firstText(root.path("result"), "suggest", "Suggest");
|
||||
if (!StringUtils.hasText(suggest)) suggest = "review";
|
||||
reason = firstText(root, "errmsg", "reason");
|
||||
if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调";
|
||||
extra = firstText(root, "extra", "Extra");
|
||||
Long taskId;
|
||||
try {
|
||||
taskId = contentModerationForwardService.persistCallback(decoded);
|
||||
} catch (RuntimeException exception) {
|
||||
response.setStatus(500);
|
||||
log.error("微信审核回调落库失败,拒绝返回成功等待微信重试,errorType={}",
|
||||
exception.getClass().getSimpleName());
|
||||
return "persist_failed";
|
||||
}
|
||||
if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("微信审核回调缺少任务标识");
|
||||
if (claimLocally(taskId, suggest, reason, extra)) {
|
||||
return "success";
|
||||
}
|
||||
|
||||
String taskEnv = normalizeEnv(decodeTaskEnv(extra));
|
||||
String localEnv = deployProperties.getEnv();
|
||||
String forwardPayload = buildForwardPayload(taskId, suggest, reason, extra);
|
||||
if (!StringUtils.hasText(taskEnv)) {
|
||||
contentModerationForwardService.recordUnclaimed(taskId, extra, forwardPayload, "回调 extra 缺少部署环境标识");
|
||||
log.warn("微信审核回调无法认领:extra 缺少环境标识,traceId={}, sourceEnv={}, targetEnv={}, hop=0",
|
||||
taskId, localEnv, null);
|
||||
return "success";
|
||||
}
|
||||
if (taskEnv.equals(localEnv)) {
|
||||
contentModerationForwardService.recordUnclaimed(taskId, extra, forwardPayload, "本环境未匹配到审核任务");
|
||||
log.warn("微信审核回调无法认领:本环境未匹配任务,traceId={}, sourceEnv={}, targetEnv={}, hop=0",
|
||||
taskId, localEnv, taskEnv);
|
||||
return "success";
|
||||
}
|
||||
ModerationForwardConfig forwardConfig = contentModerationForwardService.runtimeConfig();
|
||||
if (!StringUtils.hasText(forwardConfig.targetFor(taskEnv))) {
|
||||
contentModerationForwardService.recordTargetMissing(taskId, localEnv, taskEnv, extra, forwardPayload);
|
||||
log.warn("微信审核回调目标环境未配置转发地址,traceId={}, sourceEnv={}, targetEnv={}, hop=0",
|
||||
taskId, localEnv, taskEnv);
|
||||
return "success";
|
||||
}
|
||||
contentModerationForwardService.enqueue(taskId, localEnv, taskEnv, extra, forwardPayload);
|
||||
contentModerationForwardService.submit(taskId);
|
||||
return "success";
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理转发进来的回调:只允许一跳,验签通过后仅在本地处理,不再二次转发。
|
||||
* 处理其它环境转发的回调:只允许一跳;验签通过后仅在本地认领,不再向外转发。
|
||||
* 应答三态:CLAIMED / NOT_MINE;验签失败、报文异常或跳数非法时抛异常(调用方归为 ERROR)。
|
||||
*/
|
||||
private String handleForwardedCallback(String forwardBy, String forwardHop, String timestamp,
|
||||
String nonce, String signature, String body) {
|
||||
String nonce, String signature, String body) throws Exception {
|
||||
if (!contentModerationForwardService.verifySignature(timestamp, nonce, signature, body)) {
|
||||
throw new IllegalArgumentException("跨环境转发签名校验失败");
|
||||
}
|
||||
String taskId;
|
||||
String suggest;
|
||||
String reason;
|
||||
String extra;
|
||||
try {
|
||||
JsonNode root = objectMapper.readTree(body == null ? "" : body);
|
||||
taskId = firstText(root, "trace_id", "traceId", "task_id");
|
||||
suggest = firstText(root, "suggest", "Suggest");
|
||||
if (!StringUtils.hasText(suggest)) suggest = "review";
|
||||
reason = firstText(root, "reason", "errmsg");
|
||||
if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调";
|
||||
extra = firstText(root, "extra", "Extra");
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalArgumentException("跨环境转发报文无法解析");
|
||||
String sourceEnv = normalizeEnv(forwardBy);
|
||||
if (!StringUtils.hasText(sourceEnv)) {
|
||||
throw new IllegalArgumentException("跨环境转发缺少来源环境");
|
||||
}
|
||||
if (sourceEnv.equals(deployProperties.getEnv())) {
|
||||
throw new IllegalArgumentException("跨环境转发来源为自身,已拒绝");
|
||||
}
|
||||
if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("跨环境转发报文缺少任务标识");
|
||||
|
||||
String hopText = forwardHop == null ? "1" : forwardHop.trim();
|
||||
int hop;
|
||||
try {
|
||||
hop = Integer.parseInt(hopText);
|
||||
hop = StringUtils.hasText(forwardHop) ? Integer.parseInt(forwardHop.trim()) : 1;
|
||||
} catch (NumberFormatException exception) {
|
||||
hop = 2;
|
||||
}
|
||||
String localEnv = deployProperties.getEnv();
|
||||
String sourceEnv = normalizeEnv(forwardBy);
|
||||
if (hop > 1 || (StringUtils.hasText(sourceEnv) && sourceEnv.equals(localEnv))) {
|
||||
contentModerationForwardService.recordUnclaimed(taskId, extra, body,
|
||||
"检测到转发环路或超过一跳,已丢弃");
|
||||
log.warn("微信审核回调转发被丢弃:环路或超过一跳,traceId={}, sourceEnv={}, targetEnv={}, hop={}",
|
||||
taskId, sourceEnv, localEnv, hop);
|
||||
return "success";
|
||||
if (hop != 1) {
|
||||
throw new IllegalArgumentException("跨环境转发跳数非法,已拒绝");
|
||||
}
|
||||
log.info("收到跨环境转发的微信审核回调,traceId={}, sourceEnv={}, targetEnv={}, hop={}",
|
||||
taskId, sourceEnv, localEnv, hop);
|
||||
if (!claimLocally(taskId, suggest, reason, extra)) {
|
||||
contentModerationForwardService.recordUnclaimed(taskId, extra, body, "转发目标环境仍未匹配到审核任务");
|
||||
log.warn("跨环境转发的微信审核回调未匹配到本地任务,traceId={}, sourceEnv={}, targetEnv={}, hop={}",
|
||||
taskId, sourceEnv, localEnv, hop);
|
||||
ParsedCallback parsed;
|
||||
try {
|
||||
parsed = parsePayload(body);
|
||||
} catch (RuntimeException exception) {
|
||||
throw new IllegalArgumentException("跨环境转发报文无法解析");
|
||||
}
|
||||
return "success";
|
||||
if (!StringUtils.hasText(parsed.traceId())) {
|
||||
throw new IllegalArgumentException("跨环境转发报文缺少任务标识");
|
||||
}
|
||||
if (!contentModerationForwardService.reserveTrace(parsed.traceId())) {
|
||||
log.info("跨环境转发重复到达,按幂等返回已认领,traceId={}, sourceEnv={}", parsed.traceId(), sourceEnv);
|
||||
return CLAIMED;
|
||||
}
|
||||
boolean claimed;
|
||||
try {
|
||||
claimed = claimLocally(parsed);
|
||||
} catch (RuntimeException exception) {
|
||||
contentModerationForwardService.releaseTrace(parsed.traceId());
|
||||
throw exception;
|
||||
}
|
||||
if (claimed) {
|
||||
log.info("跨环境转发本地认领成功,traceId={}, sourceEnv={}, targetEnv={}, hop={}",
|
||||
parsed.traceId(), sourceEnv, deployProperties.getEnv(), hop);
|
||||
return CLAIMED;
|
||||
}
|
||||
contentModerationForwardService.releaseTrace(parsed.traceId());
|
||||
log.info("跨环境转发本地未命中,traceId={}, sourceEnv={}, targetEnv={}, hop={}",
|
||||
parsed.traceId(), sourceEnv, deployProperties.getEnv(), hop);
|
||||
return NOT_MINE;
|
||||
}
|
||||
|
||||
private boolean claimLocally(String taskId, String suggest, String reason, String extra) {
|
||||
if (integrationProbeService.handleImageCallback(taskId, suggest, decodeProbeId(extra))) {
|
||||
private boolean claimLocally(ParsedCallback parsed) {
|
||||
if (integrationProbeService.handleImageCallback(parsed.traceId(), parsed.suggest(), null)) {
|
||||
return true;
|
||||
}
|
||||
return contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra));
|
||||
return contentModerationService.handleWechatImageResult(
|
||||
parsed.traceId(), parsed.suggest(), parsed.reason());
|
||||
}
|
||||
|
||||
private String buildForwardPayload(String taskId, String suggest, String reason, String extra) {
|
||||
ObjectNode payload = objectMapper.createObjectNode();
|
||||
payload.put("trace_id", taskId);
|
||||
payload.put("suggest", suggest);
|
||||
payload.put("reason", reason);
|
||||
if (StringUtils.hasText(extra)) payload.put("extra", extra);
|
||||
return payload.toString();
|
||||
}
|
||||
|
||||
private String decodeTaskEnv(String extra) {
|
||||
if (!StringUtils.hasText(extra)) return null;
|
||||
try {
|
||||
JsonNode payload = objectMapper.readTree(extra);
|
||||
return firstText(payload, "env");
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
private ParsedCallback parsePayload(String decoded) throws Exception {
|
||||
if (!StringUtils.hasText(decoded)) {
|
||||
throw new IllegalArgumentException("审核回调报文为空");
|
||||
}
|
||||
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 ParsedCallback(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 ParsedCallback(traceId, suggest, reason);
|
||||
}
|
||||
|
||||
private String normalizeEnv(String value) {
|
||||
@@ -230,26 +202,6 @@ public class WechatContentModerationCallbackController {
|
||||
return Arrays.asList("dev", "sit", "prod").contains(normalized) ? normalized : null;
|
||||
}
|
||||
|
||||
private String decodeSourceEnvVersion(String extra) {
|
||||
if (!StringUtils.hasText(extra)) return null;
|
||||
try {
|
||||
JsonNode payload = objectMapper.readTree(extra);
|
||||
return firstText(payload, "envVersion", "env_version");
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String decodeProbeId(String extra) {
|
||||
if (!StringUtils.hasText(extra)) return null;
|
||||
try {
|
||||
JsonNode payload = objectMapper.readTree(extra);
|
||||
return firstText(payload, "probeId", "probe_id");
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String extractEncryptedPayload(String body) throws Exception {
|
||||
if (!StringUtils.hasText(body)) {
|
||||
throw new IllegalArgumentException("微信审核回调消息体为空");
|
||||
@@ -293,4 +245,7 @@ public class WechatContentModerationCallbackController {
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
private record ParsedCallback(String traceId, String suggest, String reason) {
|
||||
}
|
||||
}
|
||||
|
||||
+15
-50
@@ -2,9 +2,9 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
@@ -18,6 +18,7 @@ import org.springframework.web.util.UriComponentsBuilder;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class WechatContentModerationProvider implements ContentModerationProvider {
|
||||
private static final String TEXT_CHECK_URL = "https://api.weixin.qq.com/wxa/msg_sec_check";
|
||||
@@ -27,19 +28,16 @@ public class WechatContentModerationProvider implements ContentModerationProvide
|
||||
private final ObjectMapper objectMapper;
|
||||
private final WechatMiniClientService wechatMiniClientService;
|
||||
private final ContentModerationProperties properties;
|
||||
private final SalonDeployProperties deployProperties;
|
||||
|
||||
public WechatContentModerationProvider(
|
||||
@Qualifier("wechatContentModerationRestTemplate") RestTemplate restTemplate,
|
||||
ObjectMapper objectMapper,
|
||||
WechatMiniClientService wechatMiniClientService,
|
||||
ContentModerationProperties properties,
|
||||
SalonDeployProperties deployProperties) {
|
||||
ContentModerationProperties properties) {
|
||||
this.restTemplate = restTemplate;
|
||||
this.objectMapper = objectMapper;
|
||||
this.wechatMiniClientService = wechatMiniClientService;
|
||||
this.properties = properties;
|
||||
this.deployProperties = deployProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -61,61 +59,23 @@ public class WechatContentModerationProvider implements ContentModerationProvide
|
||||
|
||||
@Override
|
||||
public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) {
|
||||
return submitImage(contentType, imageUrl, openId, "UNKNOWN");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModerationOutcome submitImage(String contentType, String imageUrl, String openId, String sourceEnvVersion) {
|
||||
return submitImageWithExtra(contentType, imageUrl, openId, encodeSourceEnvVersion(sourceEnvVersion));
|
||||
}
|
||||
|
||||
public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId, String sourceEnvVersion) {
|
||||
Map<String, String> extra = new LinkedHashMap<>();
|
||||
extra.put("env", deployProperties.getEnv());
|
||||
extra.put("envVersion", normalizeEnvVersion(sourceEnvVersion));
|
||||
extra.put("probeId", probeId);
|
||||
try {
|
||||
return submitImageWithExtra("INTEGRATION_PROBE", imageUrl, openId, objectMapper.writeValueAsString(extra));
|
||||
} catch (java.io.IOException exception) {
|
||||
throw new IllegalStateException("无法编码微信审核测试标识", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizeEnvVersion(String value) {
|
||||
if ("developer".equalsIgnoreCase(value) || "develop".equalsIgnoreCase(value)) return "develop";
|
||||
if ("trial".equalsIgnoreCase(value)) return "trial";
|
||||
if ("formal".equalsIgnoreCase(value) || "release".equalsIgnoreCase(value)) return "release";
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
private ModerationOutcome submitImageWithExtra(String contentType, String imageUrl, String openId, String extra) {
|
||||
if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核");
|
||||
if (!StringUtils.hasText(imageUrl) || !imageUrl.startsWith("https://")) {
|
||||
return retry("IMAGE_URL_INVALID", "审核图片需要短期有效的 HTTPS 地址");
|
||||
}
|
||||
// 微信 media_check_async 只接受 media_url、media_type、version、scene、openid;
|
||||
// 额外字段(如 extra)会直接返回 47001 data format error,务必不要下发。
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("media_url", imageUrl);
|
||||
payload.put("media_type", 1);
|
||||
payload.put("version", 2);
|
||||
payload.put("media_type", 2);
|
||||
payload.put("version", 1);
|
||||
payload.put("scene", properties.getScene());
|
||||
payload.put("openid", openId);
|
||||
payload.put("extra", extra);
|
||||
return parseResult(post(IMAGE_CHECK_URL, payload), true);
|
||||
}
|
||||
|
||||
private String encodeSourceEnvVersion(String sourceEnvVersion) {
|
||||
String envVersion = sourceEnvVersion;
|
||||
if (!"develop".equals(envVersion) && !"trial".equals(envVersion) && !"release".equals(envVersion)) {
|
||||
envVersion = "UNKNOWN";
|
||||
}
|
||||
Map<String, String> extra = new LinkedHashMap<>();
|
||||
extra.put("env", deployProperties.getEnv());
|
||||
extra.put("envVersion", envVersion);
|
||||
try {
|
||||
return objectMapper.writeValueAsString(extra);
|
||||
} catch (java.io.IOException exception) {
|
||||
throw new IllegalStateException("无法编码微信审核来源版本", exception);
|
||||
}
|
||||
public ModerationOutcome submitTestImage(String imageUrl, String openId) {
|
||||
return submitImage("INTEGRATION_PROBE", imageUrl, openId);
|
||||
}
|
||||
|
||||
private Map<String, Object> post(String endpoint, Map<String, Object> payload) {
|
||||
@@ -127,7 +87,12 @@ public class WechatContentModerationProvider implements ContentModerationProvide
|
||||
try {
|
||||
String response = restTemplate.postForObject(url, new HttpEntity<>(payload, headers), String.class);
|
||||
if (!StringUtils.hasText(response)) throw new IllegalStateException("微信审核服务返回空响应");
|
||||
return objectMapper.readValue(response, new TypeReference<Map<String, Object>>() {});
|
||||
Map<String, Object> body = objectMapper.readValue(response, new TypeReference<Map<String, Object>>() {});
|
||||
int errorCode = number(body.get("errcode"));
|
||||
if (errorCode != 0) {
|
||||
log.warn("微信内容审核返回错误,endpoint={}, errcode={}, errmsg={}", endpoint, errorCode, text(body.get("errmsg")));
|
||||
}
|
||||
return body;
|
||||
} catch (RestClientException | java.io.IOException exception) {
|
||||
throw new IllegalStateException("微信内容审核请求失败", exception);
|
||||
}
|
||||
|
||||
+22
-11
@@ -6,7 +6,7 @@ import com.xiaowang.jayucloud.salon.core.modules.system.vo.ModerationForwardReco
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 微信异步图片审核回调的跨环境转发。
|
||||
* 微信异步图片审核回调的持久化任务、跨环境串行探测与补偿。
|
||||
*/
|
||||
public interface ContentModerationForwardService {
|
||||
|
||||
@@ -15,29 +15,40 @@ public interface ContentModerationForwardService {
|
||||
List<ModerationForwardRecordVO> listRecent(int limit);
|
||||
|
||||
/**
|
||||
* 记录无法认领的回调(extra 缺失或指向本环境但本地没有任务),不自动重试。
|
||||
* 回调到达后第一件事:按 trace_id 落库。重复回调直接返回已有任务 ID。
|
||||
* 落库失败抛出异常,由控制器返回非 200,让微信重试。
|
||||
*/
|
||||
void recordUnclaimed(String traceId, String extraJson, String payload, String note);
|
||||
Long persistCallback(String rawPayload);
|
||||
|
||||
/**
|
||||
* 记录目标环境未配置的回调,不自动重试,配置补齐后可由补偿任务重放。
|
||||
* 提交异步执行,不影响回调响应耗时。
|
||||
*/
|
||||
void recordTargetMissing(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload);
|
||||
void submit(Long taskId);
|
||||
|
||||
/**
|
||||
* 落库为 PENDING 并异步转发,确保微信回调在 5 秒内拿到 success。
|
||||
* 执行一次任务:抢锁、幂等判断、本地认领、串行探测、写回状态。
|
||||
*/
|
||||
void enqueue(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload);
|
||||
void executeTask(Long taskId);
|
||||
|
||||
/**
|
||||
* 重放到期的 RETRY 记录,最多 5 次,指数退避。
|
||||
* 补偿扫描:把到期或锁超时的任务重新提交执行。
|
||||
*/
|
||||
int retryPending();
|
||||
int retryDueTasks();
|
||||
|
||||
/**
|
||||
* 转发配置补齐后,把对应目标环境下的 TARGET_MISSING 记录重新排队。
|
||||
* 应用启动时扫描未完成任务,避免进程重启丢消息。
|
||||
*/
|
||||
int requeueConfiguredTargets();
|
||||
int recoverPendingTasks();
|
||||
|
||||
/**
|
||||
* 处理前占位,保证同一个 trace_id 的业务处理只成功一次。
|
||||
*/
|
||||
boolean reserveTrace(String traceId);
|
||||
|
||||
/**
|
||||
* 释放占位,允许后续重试继续处理。
|
||||
*/
|
||||
void releaseTrace(String traceId);
|
||||
|
||||
/**
|
||||
* 校验转发请求的 HMAC 签名、时间窗与 nonce 防重放。
|
||||
|
||||
+1
-4
@@ -12,10 +12,7 @@ public interface ContentModerationService {
|
||||
String payloadJson, List<Long> imageFileIds);
|
||||
List<ContentModerationRecordVO> listPending();
|
||||
boolean review(Long reviewerId, Long recordId, boolean approved, String reason);
|
||||
boolean handleWechatImageResult(String providerTaskId, String suggest, String reason, String sourceEnvVersion);
|
||||
boolean handleWechatImageResult(String providerTaskId, String suggest, String reason);
|
||||
|
||||
default boolean handleWechatImageResult(String providerTaskId, String suggest, String reason) {
|
||||
return handleWechatImageResult(providerTaskId, suggest, reason, null);
|
||||
}
|
||||
int retryFailedImageTasks();
|
||||
}
|
||||
|
||||
+336
-156
@@ -2,16 +2,24 @@ 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;
|
||||
@@ -23,6 +31,8 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@@ -36,24 +46,29 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
@RequiredArgsConstructor
|
||||
public class ContentModerationForwardServiceImpl implements ContentModerationForwardService {
|
||||
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_RETRY = "RETRY";
|
||||
private static final String STATUS_FAILED = "FAILED";
|
||||
private static final String STATUS_NO_ENV = "NO_ENV";
|
||||
private static final String STATUS_TARGET_MISSING = "TARGET_MISSING";
|
||||
private static final String STATUS_FAILED = "FAILED";
|
||||
private static final String STATUS_DEAD = "DEAD";
|
||||
|
||||
private static final int MAX_RETRY = 5;
|
||||
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:";
|
||||
private static final String FORWARD_BY_HEADER = "X-Moderation-Forward-By";
|
||||
private static final String FORWARD_HOP_HEADER = "X-Moderation-Forward-Hop";
|
||||
private static final String TIMESTAMP_HEADER = "X-Timestamp";
|
||||
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 FORWARD_EXECUTOR = Executors.newFixedThreadPool(2, new ThreadFactory() {
|
||||
private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(4, new ThreadFactory() {
|
||||
@Override
|
||||
public Thread newThread(Runnable runnable) {
|
||||
Thread thread = new Thread(runnable, "moderation-forward-" + THREAD_INDEX.getAndIncrement());
|
||||
Thread thread = new Thread(runnable, "moderation-callback-" + THREAD_INDEX.getAndIncrement());
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}
|
||||
@@ -64,6 +79,12 @@ public class ContentModerationForwardServiceImpl implements ContentModerationFor
|
||||
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() {
|
||||
@@ -80,75 +101,124 @@ public class ContentModerationForwardServiceImpl implements ContentModerationFor
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recordUnclaimed(String traceId, String extraJson, String payload, String note) {
|
||||
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)) {
|
||||
log.warn("微信审核回调无法认领且缺少任务标识,note={}", note);
|
||||
return;
|
||||
traceId = "untraced-" + sha256Hex(rawPayload == null ? "" : rawPayload).substring(0, 24);
|
||||
untracedNote = "回调缺少 trace_id 或报文无法解析,已置为 DEAD 等待人工排查";
|
||||
}
|
||||
log.warn("微信审核回调无法认领,traceId={}, sourceEnv={}, targetEnv={}, hop=0, note={}",
|
||||
traceId, deployProperties.getEnv(), null, note);
|
||||
ModerationCallbackForwardDO row = build(traceId, deployProperties.getEnv(), null, extraJson, payload, STATUS_NO_ENV, note);
|
||||
saveQuietly(row);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recordTargetMissing(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload) {
|
||||
log.warn("微信审核回调目标环境未配置转发地址,traceId={}, sourceEnv={}, targetEnv={}, hop=0",
|
||||
traceId, sourceEnv, targetEnv);
|
||||
ModerationCallbackForwardDO row = build(traceId, sourceEnv, targetEnv, extraJson, payload,
|
||||
STATUS_TARGET_MISSING, "目标环境未配置转发地址");
|
||||
saveQuietly(row);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enqueue(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload) {
|
||||
ModerationCallbackForwardDO existing = findByTrace(traceId);
|
||||
if (existing != null) {
|
||||
log.info("微信审核回调转发已存在记录,traceId={}, sourceEnv={}, targetEnv={}, status={}",
|
||||
traceId, sourceEnv, targetEnv, existing.getStatus());
|
||||
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 = build(traceId, sourceEnv, targetEnv, extraJson, payload, STATUS_PENDING, null);
|
||||
if (!saveQuietly(row)) return;
|
||||
log.info("微信审核回调进入跨环境转发,traceId={}, sourceEnv={}, targetEnv={}, hop=1",
|
||||
traceId, sourceEnv, targetEnv);
|
||||
FORWARD_EXECUTOR.execute(() -> dispatchById(row.getId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Scheduled(fixedDelay = 60000)
|
||||
public int retryPending() {
|
||||
List<ModerationCallbackForwardDO> rows = forwardMapper.selectList(new LambdaQueryWrapper<ModerationCallbackForwardDO>()
|
||||
.eq(ModerationCallbackForwardDO::getStatus, STATUS_RETRY)
|
||||
.lt(ModerationCallbackForwardDO::getRetryCount, MAX_RETRY)
|
||||
.orderByAsc(ModerationCallbackForwardDO::getId)
|
||||
.last("LIMIT 50"));
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
int attempted = 0;
|
||||
for (ModerationCallbackForwardDO row : rows) {
|
||||
if (!backoffElapsed(row, now)) continue;
|
||||
attempted++;
|
||||
dispatchById(row.getId());
|
||||
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);
|
||||
}
|
||||
return attempted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int requeueConfiguredTargets() {
|
||||
ModerationForwardConfig config = runtimeConfig();
|
||||
if (!config.ready() || config.getTargets() == null || config.getTargets().isEmpty()) return 0;
|
||||
List<String> configuredEnvs = config.getTargets().entrySet().stream()
|
||||
.filter(entry -> StringUtils.hasText(entry.getValue()))
|
||||
.map(Map.Entry::getKey)
|
||||
.toList();
|
||||
if (configuredEnvs.isEmpty()) return 0;
|
||||
return forwardMapper.update(null, new UpdateWrapper<ModerationCallbackForwardDO>()
|
||||
.eq("status", STATUS_TARGET_MISSING)
|
||||
.in("target_env", configuredEnvs)
|
||||
.set("status", STATUS_RETRY)
|
||||
.set("retry_count", 0)
|
||||
.set("last_error", null)
|
||||
.set("updated_at", LocalDateTime.now()));
|
||||
@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;
|
||||
try {
|
||||
Boolean fresh = redisTemplate.opsForValue()
|
||||
.setIfAbsent(CLAIM_KEY_PREFIX + traceId, "1", CLAIM_TTL);
|
||||
return Boolean.TRUE.equals(fresh);
|
||||
} catch (RuntimeException exception) {
|
||||
log.warn("审核回调幂等占位写入失败,按未占用继续处理,traceId={}", traceId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void releaseTrace(String traceId) {
|
||||
if (!StringUtils.hasText(traceId)) return;
|
||||
try {
|
||||
redisTemplate.delete(CLAIM_KEY_PREFIX + traceId);
|
||||
} catch (RuntimeException exception) {
|
||||
log.warn("审核回调幂等占位释放失败,traceId={}", traceId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -169,78 +239,200 @@ public class ContentModerationForwardServiceImpl implements ContentModerationFor
|
||||
signature.trim().toLowerCase(java.util.Locale.ROOT).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private void dispatchById(Long id) {
|
||||
ModerationCallbackForwardDO row = forwardMapper.selectById(id);
|
||||
if (row == null || STATUS_SUCCESS.equals(row.getStatus())) return;
|
||||
@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()) {
|
||||
markFailed(row, "跨环境转发未启用或共享密钥缺失", false);
|
||||
releaseTrace(traceId);
|
||||
failOrRetry(row, owner, "跨环境转发未启用或共享密钥缺失", false);
|
||||
return;
|
||||
}
|
||||
String target = config.targetFor(row.getTargetEnv());
|
||||
if (!StringUtils.hasText(target)) {
|
||||
row.setStatus(STATUS_TARGET_MISSING);
|
||||
row.setLastError("目标环境未配置转发地址");
|
||||
row.setUpdatedAt(LocalDateTime.now());
|
||||
forwardMapper.updateById(row);
|
||||
log.warn("微信审核回调转发目标缺失,traceId={}, sourceEnv={}, targetEnv={}, hop=1",
|
||||
row.getTraceId(), row.getSourceEnv(), row.getTargetEnv());
|
||||
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 {
|
||||
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
|
||||
String nonce = UUID.randomUUID().toString().replace("-", "");
|
||||
String signature = sign(config.getSecret(), timestamp, nonce, row.getPayload() == null ? "" : row.getPayload());
|
||||
Map<String, String> headers = new java.util.HashMap<>();
|
||||
headers.put(FORWARD_BY_HEADER, deployProperties.getEnv());
|
||||
headers.put(FORWARD_HOP_HEADER, "1");
|
||||
headers.put("X-Timestamp", timestamp);
|
||||
headers.put("X-Nonce", nonce);
|
||||
headers.put("X-Signature", signature);
|
||||
boolean accepted = forwardHttpClient.post(target, row.getPayload(), headers);
|
||||
if (accepted) {
|
||||
row.setStatus(STATUS_SUCCESS);
|
||||
row.setLastError(null);
|
||||
row.setUpdatedAt(LocalDateTime.now());
|
||||
forwardMapper.updateById(row);
|
||||
log.info("微信审核回调跨环境转发成功,traceId={}, sourceEnv={}, targetEnv={}, hop=1",
|
||||
row.getTraceId(), row.getSourceEnv(), row.getTargetEnv());
|
||||
} else {
|
||||
markRetry(row, "目标环境返回异常状态");
|
||||
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);
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
markRetry(row, "目标环境不可达或请求失败");
|
||||
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 void markRetry(ModerationCallbackForwardDO row, String error) {
|
||||
int retries = (row.getRetryCount() == null ? 0 : row.getRetryCount()) + 1;
|
||||
row.setRetryCount(retries);
|
||||
row.setLastError(clip(error, 500));
|
||||
row.setStatus(retries >= MAX_RETRY ? STATUS_FAILED : STATUS_RETRY);
|
||||
row.setUpdatedAt(LocalDateTime.now());
|
||||
forwardMapper.updateById(row);
|
||||
log.warn("微信审核回调转发失败,traceId={}, sourceEnv={}, targetEnv={}, hop=1, retryCount={}, status={}",
|
||||
row.getTraceId(), row.getSourceEnv(), row.getTargetEnv(), retries, row.getStatus());
|
||||
}
|
||||
|
||||
private void markFailed(ModerationCallbackForwardDO row, String error, boolean retry) {
|
||||
if (retry) {
|
||||
markRetry(row, error);
|
||||
return;
|
||||
}
|
||||
row.setStatus(STATUS_FAILED);
|
||||
row.setLastError(clip(error, 500));
|
||||
row.setUpdatedAt(LocalDateTime.now());
|
||||
forwardMapper.updateById(row);
|
||||
log.warn("微信审核回调转发失败,traceId={}, sourceEnv={}, targetEnv={}, hop=1, status=FAILED",
|
||||
row.getTraceId(), row.getSourceEnv(), row.getTargetEnv());
|
||||
}
|
||||
|
||||
private boolean backoffElapsed(ModerationCallbackForwardDO row, LocalDateTime now) {
|
||||
if (row.getUpdatedAt() == null) return true;
|
||||
long minutes = 1L << Math.min(Math.max(row.getRetryCount() == null ? 0 : row.getRetryCount(), 0), 5);
|
||||
return !row.getUpdatedAt().plusMinutes(minutes).isAfter(now);
|
||||
private Map<String, String> buildHeaders(ModerationForwardConfig config, String sourceEnv, String payload) {
|
||||
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
|
||||
String nonce = UUID.randomUUID().toString().replace("-", "");
|
||||
String signature = sign(config.getSecret(), timestamp, nonce, payload == null ? "" : payload);
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
headers.put(FORWARD_BY_HEADER, sourceEnv);
|
||||
headers.put(FORWARD_HOP_HEADER, "1");
|
||||
headers.put(TIMESTAMP_HEADER, timestamp);
|
||||
headers.put(NONCE_HEADER, nonce);
|
||||
headers.put(SIGNATURE_HEADER, signature);
|
||||
return headers;
|
||||
}
|
||||
|
||||
private boolean reserveNonce(String nonce) {
|
||||
@@ -280,33 +472,6 @@ public class ContentModerationForwardServiceImpl implements ContentModerationFor
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private ModerationCallbackForwardDO build(String traceId, String sourceEnv, String targetEnv,
|
||||
String extraJson, 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.setExtraJson(clip(extraJson, 256));
|
||||
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>()
|
||||
@@ -314,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());
|
||||
@@ -323,19 +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);
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void shutdown() {
|
||||
FORWARD_EXECUTOR.shutdownNow();
|
||||
private record ParsedPayload(String traceId, String suggest, String reason) {
|
||||
}
|
||||
}
|
||||
|
||||
-13
@@ -205,12 +205,6 @@ public class ContentModerationServiceImpl implements ContentModerationService {
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean handleWechatImageResult(String providerTaskId, String suggest, String reason) {
|
||||
return handleWechatImageResult(providerTaskId, suggest, reason, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean handleWechatImageResult(String providerTaskId, String suggest, String reason, String sourceEnvVersion) {
|
||||
if (!StringUtils.hasText(providerTaskId)) return false;
|
||||
ContentModerationImageTaskDO candidate = imageTaskMapper.selectOne(new LambdaQueryWrapper<ContentModerationImageTaskDO>()
|
||||
.eq(ContentModerationImageTaskDO::getProviderTaskId, providerTaskId).last("LIMIT 1"));
|
||||
@@ -225,13 +219,6 @@ public class ContentModerationServiceImpl implements ContentModerationService {
|
||||
.eq(ContentModerationImageTaskDO::getProviderTaskId, providerTaskId)
|
||||
.last("FOR UPDATE"));
|
||||
if (task == null || !isReviewable(task.getStatus())) return task != null;
|
||||
String expectedEnvVersion = normalizeTaskEnvVersion(task.getSourceEnvVersion());
|
||||
if (!StringUtils.hasText(sourceEnvVersion) && !"LEGACY".equals(expectedEnvVersion)) return true;
|
||||
String callbackEnvVersion = normalizeEnvVersion(sourceEnvVersion);
|
||||
if ("LEGACY".equals(expectedEnvVersion) && !StringUtils.hasText(sourceEnvVersion)) {
|
||||
callbackEnvVersion = "LEGACY";
|
||||
}
|
||||
if (!expectedEnvVersion.equals(callbackEnvVersion)) return true;
|
||||
if ("pass".equalsIgnoreCase(suggest)) task.setStatus("APPROVED");
|
||||
else if ("risky".equalsIgnoreCase(suggest)) task.setStatus("REJECTED");
|
||||
else task.setStatus("PENDING");
|
||||
|
||||
+18
-6
@@ -8,10 +8,13 @@ import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 跨环境审核回调转发客户端,固定 3 秒超时,失败以异常抛出由上层登记重试。
|
||||
* 跨环境审核回调探测客户端。
|
||||
* 连接超时 1 秒、读取超时 2 秒,保证串行探测尽量在微信回调窗口内完成;
|
||||
* 超时、非 2xx 与无法识别的应答统一归为 {@link ModerationProbeResult#ERROR}。
|
||||
*/
|
||||
@Component
|
||||
public class ModerationForwardHttpClient {
|
||||
@@ -20,16 +23,25 @@ public class ModerationForwardHttpClient {
|
||||
|
||||
public ModerationForwardHttpClient() {
|
||||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
||||
factory.setConnectTimeout(3000);
|
||||
factory.setReadTimeout(3000);
|
||||
factory.setConnectTimeout(1000);
|
||||
factory.setReadTimeout(2000);
|
||||
this.restTemplate = new RestTemplate(factory);
|
||||
}
|
||||
|
||||
public boolean post(String url, String body, Map<String, String> headers) {
|
||||
public ModerationProbeResult probe(String url, String body, Map<String, String> headers) {
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.forEach(httpHeaders::set);
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(url, new HttpEntity<>(body, httpHeaders), String.class);
|
||||
return response.getStatusCode().is2xxSuccessful();
|
||||
try {
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(
|
||||
url, new HttpEntity<>(body, httpHeaders), String.class);
|
||||
if (!response.getStatusCode().is2xxSuccessful()) return ModerationProbeResult.ERROR;
|
||||
String text = response.getBody() == null ? "" : response.getBody().trim().toUpperCase(Locale.ROOT);
|
||||
if (ModerationProbeResult.CLAIMED.name().equals(text)) return ModerationProbeResult.CLAIMED;
|
||||
if (ModerationProbeResult.NOT_MINE.name().equals(text)) return ModerationProbeResult.NOT_MINE;
|
||||
return ModerationProbeResult.ERROR;
|
||||
} catch (RuntimeException exception) {
|
||||
return ModerationProbeResult.ERROR;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.support;
|
||||
|
||||
/**
|
||||
* 跨环境审核回调探测的三态应答。
|
||||
*/
|
||||
public enum ModerationProbeResult {
|
||||
/** 目标环境本地存在该 trace_id 的审核记录,已完成处理。 */
|
||||
CLAIMED,
|
||||
/** 目标环境本地不存在该 trace_id 的审核记录。 */
|
||||
NOT_MINE,
|
||||
/** 超时、5xx、验签失败或报文异常,不能当作“不是”。 */
|
||||
ERROR
|
||||
}
|
||||
+2
-8
@@ -93,14 +93,8 @@ public class AdminSecureIntegrationConfigController {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
try {
|
||||
secureIntegrationConfigService.saveModerationForwardConfig(currentUser, dto);
|
||||
int requeued = contentModerationForwardService.requeueConfiguredTargets();
|
||||
if (requeued > 0) {
|
||||
securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE,
|
||||
"section=CONTENT_MODERATION_FORWARD,requeued=" + requeued);
|
||||
} else {
|
||||
securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE,
|
||||
"section=CONTENT_MODERATION_FORWARD");
|
||||
}
|
||||
securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE,
|
||||
"section=CONTENT_MODERATION_FORWARD");
|
||||
SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser);
|
||||
config.setModerationForwardRecent(contentModerationForwardService.listRecent(10));
|
||||
return Result.success(config);
|
||||
|
||||
+6
@@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.salon.core.modules.system.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
@@ -24,6 +25,11 @@ public class SecureIntegrationConfigDTO {
|
||||
|
||||
private Boolean moderationForwardEnabled;
|
||||
private Map<String, String> moderationForwardTargets;
|
||||
private List<String> moderationForwardOrder;
|
||||
private String moderationForwardSecret;
|
||||
private Boolean clearModerationForwardSecret;
|
||||
/** 补偿最大重试次数(1-10),未填写使用默认值。 */
|
||||
private Integer moderationForwardMaxRetry;
|
||||
/** 补偿指数退避秒数梯度,未填写使用默认 30/120/600/3600。 */
|
||||
private List<Integer> moderationForwardBackoffSeconds;
|
||||
}
|
||||
|
||||
+12
@@ -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;
|
||||
}
|
||||
|
||||
+40
-1
@@ -4,18 +4,29 @@ import lombok.AllArgsConstructor;
|
||||
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;
|
||||
|
||||
@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(), "");
|
||||
return new ModerationForwardConfig(false, Collections.emptyMap(), "", Collections.emptyList(),
|
||||
DEFAULT_MAX_RETRY, DEFAULT_BACKOFF_SECONDS);
|
||||
}
|
||||
|
||||
public String targetFor(String env) {
|
||||
@@ -27,4 +38,32 @@ public class ModerationForwardConfig {
|
||||
public boolean ready() {
|
||||
return enabled && StringUtils.hasText(secret);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按配置顺序返回可探测的目标环境,自动排除本环境与未配置地址的环境。
|
||||
*/
|
||||
public List<String> orderedTargets(String localEnv) {
|
||||
List<String> result = new ArrayList<>();
|
||||
if (order != null) {
|
||||
for (String env : order) {
|
||||
if (targetFor(env) != null && !env.equals(localEnv) && !result.contains(env)) result.add(env);
|
||||
}
|
||||
}
|
||||
if (targets != null) {
|
||||
for (String env : targets.keySet()) {
|
||||
if (targetFor(env) != null && !env.equals(localEnv) && !result.contains(env)) result.add(env);
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-2
@@ -274,8 +274,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService {
|
||||
}
|
||||
savePendingImageProbe(mode, probeId, uploaded.providerCode(), objectName);
|
||||
pendingSaved = true;
|
||||
ModerationOutcome outcome = wechatContentModerationProvider.submitTestImage(url, openId, probeId,
|
||||
wechatMiniProperties.getSubscribeMessageMiniprogramState());
|
||||
ModerationOutcome outcome = wechatContentModerationProvider.submitTestImage(url, openId);
|
||||
String status = outcome.status() == ModerationOutcome.Status.PENDING ? "PENDING" : outcome.status() == ModerationOutcome.Status.APPROVED ? "PASS" : "FAIL";
|
||||
checks.add(new IntegrationProbeCheckVO("微信图片异步接口", status, outcome.reason()));
|
||||
awaitingCallback = "PENDING".equals(status);
|
||||
|
||||
+80
-2
@@ -25,6 +25,7 @@ import org.springframework.util.StringUtils;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -93,7 +94,12 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
|
||||
ModerationForwardConfig forwardConfig = getModerationForwardConfig();
|
||||
result.setModerationForwardEnabled(forwardConfig.isEnabled());
|
||||
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;
|
||||
@@ -192,6 +198,9 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
|
||||
+ "),必须精确指向 /api/integration/wechat/content-moderation/callback,且 HTTP 仅允许内网主机");
|
||||
}
|
||||
}
|
||||
List<String> order = normalizeForwardOrder(dto.getModerationForwardOrder(), targets);
|
||||
Map<String, String> orderedTargets = new LinkedHashMap<>();
|
||||
for (String env : order) orderedTargets.put(env, targets.get(env));
|
||||
|
||||
ModerationForwardConfig current = getModerationForwardConfig();
|
||||
String secret;
|
||||
@@ -214,10 +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", targets);
|
||||
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) {
|
||||
@@ -242,7 +257,27 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
|
||||
}
|
||||
});
|
||||
}
|
||||
return new ModerationForwardConfig(enabled, targets, node.path("secret").asText(""));
|
||||
List<String> order = new ArrayList<>();
|
||||
JsonNode orderNode = node.path("order");
|
||||
if (orderNode.isArray()) {
|
||||
orderNode.forEach(item -> {
|
||||
if (StringUtils.hasText(item.asText(""))) order.add(item.asText(""));
|
||||
});
|
||||
}
|
||||
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();
|
||||
@@ -458,6 +493,49 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化探测顺序:只保留已配置目标地址的环境,未在 order 中声明的按 dev→sit→prod 补齐。
|
||||
*/
|
||||
private List<String> normalizeForwardOrder(List<String> rawOrder, Map<String, String> targets) {
|
||||
List<String> result = new ArrayList<>();
|
||||
if (rawOrder != null) {
|
||||
for (String item : rawOrder) {
|
||||
String env = upper(item, "");
|
||||
if (targets.containsKey(env) && !result.contains(env)) result.add(env);
|
||||
}
|
||||
}
|
||||
for (String env : Arrays.asList("dev", "sit", "prod")) {
|
||||
if (targets.containsKey(env) && !result.contains(env)) result.add(env);
|
||||
}
|
||||
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。
|
||||
|
||||
+4
@@ -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;
|
||||
}
|
||||
|
||||
+3
@@ -27,7 +27,10 @@ public class SecureIntegrationConfigVO {
|
||||
|
||||
private Boolean moderationForwardEnabled;
|
||||
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;
|
||||
+3
-1
@@ -16,6 +16,7 @@ import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmen
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningBackfillOrderCreateDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.mapper.AppointmentReservationMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO;
|
||||
@@ -70,6 +71,7 @@ class PlanningServiceImplTest {
|
||||
@Mock private WechatSubscribeMessageService wechatSubscribeMessageService;
|
||||
@Mock private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
@Mock private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
@Mock private ObjectStorageFileService objectStorageFileService;
|
||||
@Mock private PhoneCrypto phoneCrypto;
|
||||
|
||||
private PlanningServiceImpl service;
|
||||
@@ -79,7 +81,7 @@ class PlanningServiceImplTest {
|
||||
service = new PlanningServiceImpl(adminScopeHelper, userMapper, userService, nailArtistInfoMapper, artistScheduleMapper,
|
||||
artistScheduleExceptionMapper, appointmentReservationMapper, orderMapper, orderItemMapper,
|
||||
productMapper, shopMapper, shopBusinessExpiryService, shopBusinessScheduleService, appointmentCapacityService, orderService, wechatSubscribeMessageService, snowflakeIdGenerator,
|
||||
objectStorageUrlSupport, phoneCrypto);
|
||||
objectStorageUrlSupport, objectStorageFileService, phoneCrypto);
|
||||
ShopBusinessHoursDayVO defaultOpenDay = new ShopBusinessHoursDayVO();
|
||||
defaultOpenDay.setOpen(true);
|
||||
defaultOpenDay.setStartTime("10:00");
|
||||
|
||||
+156
-147
@@ -6,24 +6,25 @@ import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties;
|
||||
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.WechatCallbackCrypto;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig;
|
||||
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;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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;
|
||||
@@ -61,8 +62,6 @@ class WechatContentModerationCallbackControllerTest {
|
||||
new ModerationRuntimeConfig("WECHAT", "https://sit.example.test" + CALLBACK_PATH, "callback-token", "encoding-aes-key", true));
|
||||
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
|
||||
when(crypto.verifyPlain("callback-token", "1000", "nonce", "plain-signature")).thenReturn(true);
|
||||
WechatMiniProperties wechatProperties = new WechatMiniProperties();
|
||||
wechatProperties.setAppId("mini-app-id");
|
||||
WechatContentModerationCallbackController controller = controller(secureConfig, crypto,
|
||||
mock(ContentModerationService.class), mock(IntegrationProbeService.class),
|
||||
mock(ContentModerationForwardService.class));
|
||||
@@ -72,17 +71,16 @@ class WechatContentModerationCallbackControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void localHitDoesNotForward() 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);
|
||||
when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id"))
|
||||
.thenReturn("{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"},\"extra\":\"{\\\"env\\\":\\\"prod\\\",\\\"envVersion\\\":\\\"trial\\\"}\"}");
|
||||
when(moderationService.handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial")).thenReturn(true);
|
||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
|
||||
mock(IntegrationProbeService.class), forwardService)).build();
|
||||
String decoded = "{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"}}";
|
||||
when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id")).thenReturn(decoded);
|
||||
when(forwardService.persistCallback(decoded)).thenReturn(42L);
|
||||
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")
|
||||
@@ -94,28 +92,79 @@ class WechatContentModerationCallbackControllerTest {
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("success"));
|
||||
|
||||
verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature");
|
||||
verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial");
|
||||
verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
|
||||
verify(forwardService, never()).recordUnclaimed(anyString(), any(), any(), anyString());
|
||||
InOrder order = inOrder(forwardService);
|
||||
order.verify(forwardService).persistCallback(decoded);
|
||||
order.verify(forwardService).submit(42L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void callbackReturnsNon200WhenPersistFails() throws Exception {
|
||||
SecureIntegrationConfigService secureConfig = readyWechatConfig();
|
||||
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.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-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")
|
||||
.param("nonce", "nonce")
|
||||
.param("msg_signature", "message-signature")
|
||||
.param("encrypt_type", "aes")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"Encrypt\":\"encrypted-json\"}"))
|
||||
.andExpect(status().isInternalServerError())
|
||||
.andExpect(content().string("persist_failed"));
|
||||
|
||||
verify(forwardService, never()).submit(any());
|
||||
verify(forwardService, never()).reserveTrace(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateCallbackReusesTaskAndStillReturnsSuccess() throws Exception {
|
||||
SecureIntegrationConfigService secureConfig = readyWechatConfig();
|
||||
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.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.persistCallback(anyString())).thenReturn(7L);
|
||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto,
|
||||
mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build();
|
||||
|
||||
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(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><extra>{"env":"prod","envVersion":"release"}</extra></xml>";
|
||||
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(crypto.value(decodedXml, "extra")).thenReturn("{\"env\":\"prod\",\"envVersion\":\"release\"}");
|
||||
when(moderationService.handleWechatImageResult("task-xml", "review", "微信异步图片审核回调", "release")).thenReturn(true);
|
||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService,
|
||||
mock(IntegrationProbeService.class), mock(ContentModerationForwardService.class))).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")
|
||||
@@ -127,138 +176,102 @@ class WechatContentModerationCallbackControllerTest {
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("success"));
|
||||
|
||||
verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature");
|
||||
verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调", "release");
|
||||
verify(forwardService).persistCallback(decodedXml);
|
||||
verify(forwardService).submit(11L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void probeHitSkipsModerationAndForwarding() throws Exception {
|
||||
SecureIntegrationConfigService secureConfig = readyWechatConfig();
|
||||
WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class);
|
||||
IntegrationProbeService probeService = mock(IntegrationProbeService.class);
|
||||
void forwardedCallbackClaimsLocally() throws Exception {
|
||||
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\",\"extra\":\"{\\\"env\\\":\\\"prod\\\",\\\"probeId\\\":\\\"probe-1\\\"}\"}");
|
||||
when(probeService.handleImageCallback("probe-1", "review", "probe-1")).thenReturn(true);
|
||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto,
|
||||
mock(ContentModerationService.class), probeService, 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(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherEnvironmentCallbackIsEnqueuedAndReturnsSuccessImmediately() 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-prod\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\"}\"}");
|
||||
when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false);
|
||||
when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of("prod", "https://prod.example.test" + CALLBACK_PATH)));
|
||||
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(forwardService).enqueue(eq("task-prod"), eq("sit"), eq("prod"), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingTargetReturnsSuccessAndRecordsTargetMissing() 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-prod\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\"}\"}");
|
||||
when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false);
|
||||
when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of()));
|
||||
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(forwardService).recordTargetMissing(eq("task-prod"), eq("sit"), eq("prod"), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extraWithoutEnvIsRecordedAsNoEnvAndNotForwarded() 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-unknown\",\"suggest\":\"review\",\"extra\":\"{\\\"envVersion\\\":\\\"trial\\\"}\"}");
|
||||
when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false);
|
||||
when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of("prod", "https://prod.example.test" + CALLBACK_PATH)));
|
||||
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(forwardService).recordUnclaimed(eq("task-unknown"), anyString(), anyString(), anyString());
|
||||
verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void secondHopOrSelfForwardIsDroppedAndRecorded() throws Exception {
|
||||
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
||||
when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
|
||||
when(forwardService.reserveTrace("task-claim")).thenReturn(true);
|
||||
when(moderationService.handleWechatImageResult("task-claim", "review", "微信异步图片审核回调")).thenReturn(true);
|
||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(readyWechatConfig(), mock(WechatCallbackCrypto.class),
|
||||
mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build();
|
||||
moderationService, mock(IntegrationProbeService.class), forwardService)).build();
|
||||
|
||||
mvc.perform(post("/integration/wechat/content-moderation/callback")
|
||||
.header("X-Moderation-Forward-By", "sit")
|
||||
.header("X-Moderation-Forward-Hop", "2")
|
||||
.header("X-Moderation-Forward-By", "prod")
|
||||
.header("X-Moderation-Forward-Hop", "1")
|
||||
.header("X-Timestamp", "1000")
|
||||
.header("X-Nonce", "forward-nonce")
|
||||
.header("X-Signature", "forward-signature")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"trace_id\":\"loop-task\",\"suggest\":\"review\"}"))
|
||||
.content("{\"trace_id\":\"task-claim\",\"suggest\":\"review\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("success"));
|
||||
.andExpect(content().string("CLAIMED"));
|
||||
|
||||
verify(forwardService).recordUnclaimed(eq("loop-task"), any(), anyString(), anyString());
|
||||
verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString());
|
||||
verify(forwardService, never()).submit(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardedCallbackReturnsNotMineWhenLocalMiss() throws Exception {
|
||||
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
||||
ContentModerationService moderationService = mock(ContentModerationService.class);
|
||||
when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
|
||||
when(forwardService.reserveTrace("task-other")).thenReturn(true);
|
||||
when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString())).thenReturn(false);
|
||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(readyWechatConfig(), mock(WechatCallbackCrypto.class),
|
||||
moderationService, mock(IntegrationProbeService.class), forwardService)).build();
|
||||
|
||||
mvc.perform(post("/integration/wechat/content-moderation/callback")
|
||||
.header("X-Moderation-Forward-By", "prod")
|
||||
.header("X-Moderation-Forward-Hop", "1")
|
||||
.header("X-Timestamp", "1000")
|
||||
.header("X-Nonce", "forward-nonce")
|
||||
.header("X-Signature", "forward-signature")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"trace_id\":\"task-other\",\"suggest\":\"review\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("NOT_MINE"));
|
||||
|
||||
verify(forwardService).releaseTrace("task-other");
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardedDuplicateReturnsClaimed() throws Exception {
|
||||
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
||||
when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
|
||||
when(forwardService.reserveTrace("task-dup-forward")).thenReturn(false);
|
||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(readyWechatConfig(), mock(WechatCallbackCrypto.class),
|
||||
mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build();
|
||||
|
||||
mvc.perform(post("/integration/wechat/content-moderation/callback")
|
||||
.header("X-Moderation-Forward-By", "prod")
|
||||
.header("X-Moderation-Forward-Hop", "1")
|
||||
.header("X-Timestamp", "1000")
|
||||
.header("X-Nonce", "forward-nonce")
|
||||
.header("X-Signature", "forward-signature")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"trace_id\":\"task-dup-forward\",\"suggest\":\"review\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("CLAIMED"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardedHopGreaterThanOneIsRejected() {
|
||||
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
||||
when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
|
||||
WechatContentModerationCallbackController controller = controller(readyWechatConfig(),
|
||||
mock(WechatCallbackCrypto.class), mock(ContentModerationService.class),
|
||||
mock(IntegrationProbeService.class), forwardService);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> controller.callback(null, null, null, null, null,
|
||||
"prod", "2", "1000", "forward-nonce", "forward-signature",
|
||||
"{\"trace_id\":\"loop-task\"}", new MockHttpServletResponse()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardedSourceEqualToSelfIsRejected() {
|
||||
ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class);
|
||||
when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
|
||||
WechatContentModerationCallbackController controller = controller(readyWechatConfig(),
|
||||
mock(WechatCallbackCrypto.class), mock(ContentModerationService.class),
|
||||
mock(IntegrationProbeService.class), forwardService);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> controller.callback(null, null, null, null, null,
|
||||
"sit", "1", "1000", "forward-nonce", "forward-signature",
|
||||
"{\"trace_id\":\"self-task\"}", new MockHttpServletResponse()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -271,11 +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\"}"));
|
||||
}
|
||||
|
||||
private ModerationForwardConfig forwardConfig(Map<String, String> targets) {
|
||||
return new ModerationForwardConfig(true, targets, "forward-secret-key-01");
|
||||
"{\"trace_id\":\"task-1\"}", new MockHttpServletResponse()));
|
||||
}
|
||||
|
||||
private SecureIntegrationConfigService readyWechatConfig() {
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class WechatContentModerationProviderTest {
|
||||
@Test
|
||||
void textReviewSendsWechatIdentityAndSceneAndAcceptsOnlyExplicitPass() {
|
||||
RestTemplate restTemplate = mock(RestTemplate.class);
|
||||
WechatMiniClientService wechatClient = mock(WechatMiniClientService.class);
|
||||
when(wechatClient.getAccessTokenForContentModeration()).thenReturn("cached-token");
|
||||
when(restTemplate.postForObject(anyString(), any(HttpEntity.class), eq(String.class)))
|
||||
.thenReturn("{\"errcode\":0,\"result\":{\"suggest\":\"pass\"}}");
|
||||
ContentModerationProperties properties = new ContentModerationProperties();
|
||||
properties.setScene(3);
|
||||
WechatContentModerationProvider provider = provider(restTemplate, wechatClient, properties);
|
||||
|
||||
ModerationOutcome outcome = provider.reviewText("COMMENT", "内容", "openid-1");
|
||||
|
||||
assertEquals(ModerationOutcome.Status.APPROVED, outcome.status());
|
||||
ArgumentCaptor<HttpEntity> requestCaptor = ArgumentCaptor.forClass(HttpEntity.class);
|
||||
verify(restTemplate).postForObject(org.mockito.ArgumentMatchers.contains("access_token=cached-token"),
|
||||
requestCaptor.capture(), eq(String.class));
|
||||
Map<?, ?> payload = (Map<?, ?>) requestCaptor.getValue().getBody();
|
||||
assertEquals("内容", payload.get("content"));
|
||||
assertEquals("openid-1", payload.get("openid"));
|
||||
assertEquals(3, payload.get("scene"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void imageReviewSendsImageTypeAndDoesNotSendUnsupportedExtraField() {
|
||||
RestTemplate restTemplate = mock(RestTemplate.class);
|
||||
WechatMiniClientService wechatClient = mock(WechatMiniClientService.class);
|
||||
when(wechatClient.getAccessTokenForContentModeration()).thenReturn("cached-token");
|
||||
when(restTemplate.postForObject(anyString(), any(HttpEntity.class), eq(String.class)))
|
||||
.thenReturn("{\"errcode\":0,\"trace_id\":\"task-123\"}");
|
||||
WechatContentModerationProvider provider = provider(restTemplate, wechatClient, new ContentModerationProperties());
|
||||
|
||||
ModerationOutcome outcome = provider.submitImage("PRODUCT", "https://storage.test/signed/image", "openid-1", "trial");
|
||||
|
||||
assertEquals(ModerationOutcome.Status.PENDING, outcome.status());
|
||||
assertEquals("task-123", outcome.remoteTaskId());
|
||||
ArgumentCaptor<HttpEntity> requestCaptor = ArgumentCaptor.forClass(HttpEntity.class);
|
||||
verify(restTemplate).postForObject(anyString(), requestCaptor.capture(), eq(String.class));
|
||||
Map<?, ?> payload = (Map<?, ?>) requestCaptor.getValue().getBody();
|
||||
assertEquals("https://storage.test/signed/image", payload.get("media_url"));
|
||||
assertEquals(2, payload.get("media_type"));
|
||||
assertEquals(1, payload.get("version"));
|
||||
assertEquals("openid-1", payload.get("openid"));
|
||||
assertFalse(payload.containsKey("extra"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testImageUsesSameSupportedFieldSet() {
|
||||
RestTemplate restTemplate = mock(RestTemplate.class);
|
||||
WechatMiniClientService wechatClient = mock(WechatMiniClientService.class);
|
||||
when(wechatClient.getAccessTokenForContentModeration()).thenReturn("cached-token");
|
||||
when(restTemplate.postForObject(anyString(), any(HttpEntity.class), eq(String.class)))
|
||||
.thenReturn("{\"errcode\":0,\"trace_id\":\"probe-task\"}");
|
||||
WechatContentModerationProvider provider = provider(restTemplate, wechatClient, new ContentModerationProperties());
|
||||
|
||||
provider.submitTestImage("https://storage.test/signed/image", "private-open-id");
|
||||
|
||||
ArgumentCaptor<HttpEntity> requestCaptor = ArgumentCaptor.forClass(HttpEntity.class);
|
||||
verify(restTemplate).postForObject(anyString(), requestCaptor.capture(), eq(String.class));
|
||||
Map<?, ?> payload = (Map<?, ?>) requestCaptor.getValue().getBody();
|
||||
assertEquals(2, payload.get("media_type"));
|
||||
assertEquals(1, payload.get("version"));
|
||||
assertFalse(payload.containsKey("extra"));
|
||||
}
|
||||
|
||||
private WechatContentModerationProvider provider(RestTemplate restTemplate,
|
||||
WechatMiniClientService wechatClient,
|
||||
ContentModerationProperties properties) {
|
||||
return new WechatContentModerationProvider(restTemplate, new ObjectMapper(), wechatClient, properties);
|
||||
}
|
||||
}
|
||||
+338
-98
@@ -1,172 +1,412 @@
|
||||
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;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
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;
|
||||
|
||||
class ContentModerationForwardServiceImplTest {
|
||||
private static final String SECRET = "forward-secret-key-01";
|
||||
private static final String TARGET = "https://prod.example.test/api/integration/wechat/content-moderation/callback";
|
||||
private static final String SECRET = "forward-secret-1234567890";
|
||||
private static final String DEV_TARGET = "https://dev.example.test/api/integration/wechat/content-moderation/callback";
|
||||
private static final String PROD_TARGET = "https://prod.example.test/api/integration/wechat/content-moderation/callback";
|
||||
|
||||
private ModerationCallbackForwardMapper forwardMapper;
|
||||
private SecureIntegrationConfigService secureConfig;
|
||||
private ModerationForwardHttpClient httpClient;
|
||||
private SecureIntegrationConfigService secureIntegrationConfigService;
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
private ValueOperations<String, Object> valueOperations;
|
||||
private ModerationForwardHttpClient forwardHttpClient;
|
||||
private IntegrationProbeService probeService;
|
||||
private ContentModerationService moderationService;
|
||||
private ContentModerationForwardServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings("unchecked")
|
||||
void setUp() {
|
||||
forwardMapper = mock(ModerationCallbackForwardMapper.class);
|
||||
secureConfig = mock(SecureIntegrationConfigService.class);
|
||||
httpClient = mock(ModerationForwardHttpClient.class);
|
||||
secureIntegrationConfigService = mock(SecureIntegrationConfigService.class);
|
||||
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);
|
||||
when(secureConfig.getModerationForwardConfig())
|
||||
.thenReturn(new ModerationForwardConfig(true, Map.of("prod", TARGET), SECRET));
|
||||
SalonDeployProperties deployProperties = new SalonDeployProperties();
|
||||
deployProperties.setEnv("sit");
|
||||
service = new ContentModerationForwardServiceImpl(forwardMapper, secureConfig, deployProperties,
|
||||
redisTemplate, httpClient);
|
||||
service = new ContentModerationForwardServiceImpl(forwardMapper, secureIntegrationConfigService,
|
||||
deployProperties, redisTemplate, forwardHttpClient, probeService, moderationService,
|
||||
new ObjectMapper(), mock(WechatCallbackCrypto.class));
|
||||
}
|
||||
|
||||
// ---------- 接收侧:先落库 ----------
|
||||
|
||||
@Test
|
||||
void persistCallbackInsertsPendingTaskWithDecodedPayload() {
|
||||
doAnswer(invocation -> {
|
||||
ModerationCallbackForwardDO row = invocation.getArgument(0);
|
||||
row.setId(101L);
|
||||
return 1;
|
||||
}).when(forwardMapper).insert(any(ModerationCallbackForwardDO.class));
|
||||
|
||||
Long taskId = service.persistCallback("{\"trace_id\":\"trace-1\",\"result\":{\"suggest\":\"review\"}}");
|
||||
|
||||
assertEquals(101L, taskId);
|
||||
ModerationCallbackForwardDO row = capturedInsert();
|
||||
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 acceptsValidHmacSignature() throws Exception {
|
||||
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);
|
||||
|
||||
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());
|
||||
UpdateWrapper<ModerationCallbackForwardDO> outcome = outcomeWrapper();
|
||||
assertTrue(outcome.getParamNameValuePairs().containsValue("SUCCESS"));
|
||||
assertTrue(outcome.getParamNameValuePairs().containsValue("prod"));
|
||||
}
|
||||
|
||||
@Test
|
||||
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());
|
||||
|
||||
service.executeTask(3L);
|
||||
|
||||
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 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();
|
||||
|
||||
service.executeTask(4L);
|
||||
|
||||
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 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);
|
||||
|
||||
service.executeTask(5L);
|
||||
|
||||
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 executeTaskSkipsWhenClaimLosesToAnotherInstance() {
|
||||
ModerationCallbackForwardDO row = row(6L, "trace-locked", "PENDING", 0);
|
||||
when(forwardMapper.selectById(6L)).thenReturn(row);
|
||||
when(forwardMapper.update(isNull(), any())).thenReturn(0);
|
||||
|
||||
service.executeTask(6L);
|
||||
|
||||
verify(forwardMapper, times(1)).selectById(6L);
|
||||
verify(probeService, never()).handleImageCallback(anyString(), anyString(), any());
|
||||
verify(moderationService, never()).handleWechatImageResult(anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
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));
|
||||
|
||||
assertEquals(2, service.recoverPendingTasks());
|
||||
}
|
||||
|
||||
@Test
|
||||
void retryDueTasksDispatchesDueRecords() {
|
||||
when(forwardMapper.selectList(any())).thenReturn(Collections.singletonList(row(9L, "trace-due", "NO_ENV", 1)));
|
||||
|
||||
assertEquals(1, service.retryDueTasks());
|
||||
}
|
||||
|
||||
// ---------- Redis 幂等占位 ----------
|
||||
|
||||
@Test
|
||||
void reserveTraceReturnsFalseForDuplicate() {
|
||||
when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(false);
|
||||
|
||||
assertFalse(service.reserveTrace("trace-dup"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reserveTraceFailsOpenWhenRedisUnavailable() {
|
||||
when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class)))
|
||||
.thenThrow(new IllegalStateException("redis down"));
|
||||
|
||||
assertTrue(service.reserveTrace("trace-redis-down"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void releaseTraceDeletesClaimKey() {
|
||||
service.releaseTrace("trace-release");
|
||||
|
||||
verify(redisTemplate).delete("salon:content-moderation:claim:trace-release");
|
||||
}
|
||||
|
||||
// ---------- 转发验签 ----------
|
||||
|
||||
@Test
|
||||
void verifySignatureAcceptsValidRequest() {
|
||||
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev")));
|
||||
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
|
||||
String nonce = "nonce-valid";
|
||||
String body = "{\"trace_id\":\"task-1\"}";
|
||||
String nonce = "nonce-1";
|
||||
String body = "{\"trace_id\":\"trace-1\"}";
|
||||
String signature = sign(SECRET, timestamp, nonce, body);
|
||||
|
||||
assertTrue(service.verifySignature(timestamp, nonce, signature, body));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInvalidHmacSignature() {
|
||||
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
|
||||
|
||||
assertFalse(service.verifySignature(timestamp, "nonce-bad", "deadbeef", "{\"trace_id\":\"task-1\"}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsExpiredTimestamp() {
|
||||
void verifySignatureRejectsExpiredTimestamp() {
|
||||
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev")));
|
||||
String timestamp = String.valueOf(System.currentTimeMillis() / 1000 - 600);
|
||||
|
||||
assertFalse(service.verifySignature(timestamp, "nonce-expired", "deadbeef", "{}"));
|
||||
assertFalse(service.verifySignature(timestamp, "nonce-2", "bad", "{}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void retryPendingMarksSuccessWhenTargetAccepts() {
|
||||
void verifySignatureRejectsReplayedNonce() {
|
||||
when(secureIntegrationConfigService.getModerationForwardConfig()).thenReturn(config(Arrays.asList("dev")));
|
||||
when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(false);
|
||||
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
|
||||
String body = "{}";
|
||||
String signature = sign(SECRET, timestamp, "nonce-3", body);
|
||||
|
||||
assertFalse(service.verifySignature(timestamp, "nonce-3", signature, body));
|
||||
}
|
||||
|
||||
private ModerationForwardConfig config(List<String> order) {
|
||||
Map<String, String> targets = new LinkedHashMap<>();
|
||||
targets.put("dev", DEV_TARGET);
|
||||
targets.put("prod", PROD_TARGET);
|
||||
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(11L);
|
||||
row.setTraceId("task-retry");
|
||||
row.setId(id);
|
||||
row.setTraceId(traceId);
|
||||
row.setPayload("{\"trace_id\":\"" + traceId + "\",\"result\":{\"suggest\":\"review\"}}");
|
||||
row.setSourceEnv("sit");
|
||||
row.setTargetEnv("prod");
|
||||
row.setStatus("RETRY");
|
||||
row.setRetryCount(1);
|
||||
row.setUpdatedAt(LocalDateTime.now().minusMinutes(5));
|
||||
row.setPayload("{\"trace_id\":\"task-retry\"}");
|
||||
when(forwardMapper.selectList(any())).thenReturn(List.of(row));
|
||||
when(forwardMapper.selectById(11L)).thenReturn(row);
|
||||
when(httpClient.post(anyString(), anyString(), any())).thenReturn(true);
|
||||
|
||||
int attempted = service.retryPending();
|
||||
|
||||
assertEquals(1, attempted);
|
||||
assertEquals("SUCCESS", row.getStatus());
|
||||
verify(forwardMapper).updateById(row);
|
||||
row.setStatus(status);
|
||||
row.setRetryCount(retryCount);
|
||||
row.setCreatedAt(LocalDateTime.now().minusMinutes(10));
|
||||
return row;
|
||||
}
|
||||
|
||||
@Test
|
||||
void retryFailureIncrementsCountAndKeepsRetry() {
|
||||
ModerationCallbackForwardDO row = new ModerationCallbackForwardDO();
|
||||
row.setId(12L);
|
||||
row.setTraceId("task-fail");
|
||||
row.setSourceEnv("sit");
|
||||
row.setTargetEnv("prod");
|
||||
row.setStatus("RETRY");
|
||||
row.setRetryCount(0);
|
||||
row.setUpdatedAt(null);
|
||||
row.setPayload("{\"trace_id\":\"task-fail\"}");
|
||||
when(forwardMapper.selectList(any())).thenReturn(List.of(row));
|
||||
when(forwardMapper.selectById(12L)).thenReturn(row);
|
||||
when(httpClient.post(anyString(), anyString(), any())).thenThrow(new IllegalStateException("timeout"));
|
||||
|
||||
service.retryPending();
|
||||
|
||||
assertEquals("RETRY", row.getStatus());
|
||||
assertEquals(1, row.getRetryCount());
|
||||
assertEquals("目标环境不可达或请求失败", row.getLastError());
|
||||
}
|
||||
|
||||
@Test
|
||||
void targetMissingIsRecordedWithoutRetryQueue() {
|
||||
service.recordTargetMissing("task-missing", "sit", "prod", "{\"env\":\"prod\"}", "{}");
|
||||
|
||||
private ModerationCallbackForwardDO capturedInsert() {
|
||||
ArgumentCaptor<ModerationCallbackForwardDO> captor = ArgumentCaptor.forClass(ModerationCallbackForwardDO.class);
|
||||
verify(forwardMapper).insert(captor.capture());
|
||||
ModerationCallbackForwardDO saved = captor.getValue();
|
||||
assertEquals("TARGET_MISSING", saved.getStatus());
|
||||
assertEquals("prod", saved.getTargetEnv());
|
||||
assertEquals(0, saved.getRetryCount());
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingExtraIsRecordedAsNoEnv() {
|
||||
service.recordUnclaimed("task-noenv", "{\"envVersion\":\"trial\"}", "{}", "回调 extra 缺少部署环境标识");
|
||||
|
||||
ArgumentCaptor<ModerationCallbackForwardDO> captor = ArgumentCaptor.forClass(ModerationCallbackForwardDO.class);
|
||||
verify(forwardMapper).insert(captor.capture());
|
||||
assertEquals("NO_ENV", captor.getValue().getStatus());
|
||||
assertEquals("sit", captor.getValue().getSourceEnv());
|
||||
@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);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requeueMovesTargetMissingToRetryForConfiguredTargets() {
|
||||
when(forwardMapper.update(any(), any())).thenReturn(2);
|
||||
|
||||
int requeued = service.requeueConfiguredTargets();
|
||||
|
||||
assertEquals(2, requeued);
|
||||
verify(forwardMapper).update(org.mockito.ArgumentMatchers.isNull(), any());
|
||||
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 String sign(String secret, String timestamp, String nonce, String body) throws Exception {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
StringBuilder bodyHash = new StringBuilder();
|
||||
for (byte item : digest.digest(body.getBytes(StandardCharsets.UTF_8))) bodyHash.append(String.format("%02x", item));
|
||||
String canonical = timestamp + "\n" + nonce + "\n" + bodyHash;
|
||||
javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256");
|
||||
mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (byte item : mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8))) result.append(String.format("%02x", item));
|
||||
return result.toString();
|
||||
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");
|
||||
mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
String canonical = timestamp + "\n" + nonce + "\n" + sha256Hex(body);
|
||||
byte[] digest = mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (byte item : digest) builder.append(String.format("%02x", item));
|
||||
return builder.toString();
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String sha256Hex(String value) {
|
||||
try {
|
||||
java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA-256");
|
||||
byte[] bytes = digest.digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (byte item : bytes) builder.append(String.format("%02x", item));
|
||||
return builder.toString();
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-15
@@ -122,7 +122,7 @@ class IntegrationProbeServiceImplTest {
|
||||
|
||||
assertEquals("PENDING", result.getStatus());
|
||||
verify(storageProvider, never()).uploadStream(any(), anyLong(), any(), any());
|
||||
verify(moderationProvider, never()).submitTestImage(any(), any(), any(), any());
|
||||
verify(moderationProvider, never()).submitTestImage(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -132,15 +132,16 @@ class IntegrationProbeServiceImplTest {
|
||||
.thenReturn("{\"errcode\":0,\"trace_id\":\"probe-task\"}");
|
||||
WechatContentModerationProvider provider = new WechatContentModerationProvider(
|
||||
restTemplate, new ObjectMapper(), wechatClient,
|
||||
new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties(),
|
||||
deployProperties());
|
||||
new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties());
|
||||
|
||||
provider.submitTestImage("https://storage.test/probe.png", "private-open-id", "probe-1", "trial");
|
||||
provider.submitTestImage("https://storage.test/probe.png", "private-open-id");
|
||||
|
||||
ArgumentCaptor<HttpEntity> requestCaptor = ArgumentCaptor.forClass(HttpEntity.class);
|
||||
verify(restTemplate).postForObject(anyString(), requestCaptor.capture(), eq(String.class));
|
||||
Map<?, ?> payload = (Map<?, ?>) requestCaptor.getValue().getBody();
|
||||
assertEquals(1, payload.get("media_type"));
|
||||
assertEquals(2, payload.get("media_type"));
|
||||
assertEquals(1, payload.get("version"));
|
||||
org.junit.jupiter.api.Assertions.assertFalse(payload.containsKey("extra"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -150,22 +151,14 @@ class IntegrationProbeServiceImplTest {
|
||||
.thenReturn("{\"errcode\":47001}");
|
||||
WechatContentModerationProvider provider = new WechatContentModerationProvider(
|
||||
restTemplate, new ObjectMapper(), wechatClient,
|
||||
new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties(),
|
||||
deployProperties());
|
||||
new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties());
|
||||
|
||||
var result = provider.submitTestImage("https://storage.test/probe.png", "private-open-id", "probe-1", "trial");
|
||||
var result = provider.submitTestImage("https://storage.test/probe.png", "private-open-id");
|
||||
|
||||
assertEquals("47001", result.code());
|
||||
assertEquals("微信审核请求参数格式无效,请核对接口字段", result.reason());
|
||||
}
|
||||
|
||||
private com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties deployProperties() {
|
||||
com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties properties =
|
||||
new com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties();
|
||||
properties.setEnv("sit");
|
||||
return properties;
|
||||
}
|
||||
|
||||
private UserDO admin() {
|
||||
UserDO user = new UserDO();
|
||||
user.setId(1L);
|
||||
|
||||
@@ -1596,7 +1596,10 @@ export interface SecureIntegrationConfigVO {
|
||||
mockProviderAllowed: boolean
|
||||
moderationForwardEnabled?: boolean
|
||||
moderationForwardTargets?: Record<string, string>
|
||||
moderationForwardOrder?: string[]
|
||||
moderationForwardSecretConfigured?: boolean
|
||||
moderationForwardMaxRetry?: number
|
||||
moderationForwardBackoffSeconds?: number[]
|
||||
moderationForwardRecent?: ModerationForwardRecordVO[]
|
||||
encryptionKeyConfigured: boolean
|
||||
updatedAt?: string
|
||||
@@ -1608,9 +1611,12 @@ export interface ModerationForwardRecordVO {
|
||||
traceId: string
|
||||
sourceEnv?: string
|
||||
targetEnv?: string
|
||||
status: 'PENDING' | 'SUCCESS' | 'RETRY' | 'FAILED' | 'NO_ENV' | '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
|
||||
}
|
||||
@@ -1658,8 +1664,11 @@ export interface SecureIntegrationConfigUpdate {
|
||||
clearModerationEncodingAesKey?: boolean
|
||||
moderationForwardEnabled?: boolean
|
||||
moderationForwardTargets?: Record<string, string>
|
||||
moderationForwardOrder?: string[]
|
||||
moderationForwardSecret?: string
|
||||
clearModerationForwardSecret?: boolean
|
||||
moderationForwardMaxRetry?: number
|
||||
moderationForwardBackoffSeconds?: number[]
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -55,7 +55,9 @@
|
||||
</div>
|
||||
<a-table :columns="moderationColumns" :data-source="moderation" :loading="moderationLoading" row-key="id" :scroll="{ x: 'max-content' }">
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'type'">{{ moderationType(record.contentType) }}</template>
|
||||
<template v-if="column.key === 'type'">
|
||||
<span :title="isUnknownModerationType(record.contentType) ? record.contentType : undefined">{{ moderationType(record.contentType) }}</span>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'content'">
|
||||
<div class="moderation-content">
|
||||
<div class="moderation-author">{{ record.authorName || '未知发布者' }}</div>
|
||||
@@ -323,8 +325,36 @@ function runBackfill() {
|
||||
})
|
||||
}
|
||||
|
||||
function moderationType(type: string) {
|
||||
return ({ USER_PROFILE: '个人资料', USER_AVATAR: '头像', PRODUCT: '作品', EFFECT_DIAGRAM: '效果图', COMMENT: '评论', ORDER_ARTIST_REVIEW: '订单评价', SHOP: '门店资料', ANNOUNCEMENT: '公告', SYSTEM_MESSAGE: '系统消息' } as Record<string, string>)[type] || type
|
||||
// 内容复核类型枚举(t_content_moderation_record.content_type)中文映射,集中在此维护
|
||||
const MODERATION_TYPE_LABELS: Record<string, string> = {
|
||||
USER_PROFILE: '个人资料',
|
||||
USER_AVATAR: '头像',
|
||||
NAIL_ARTIST_PROFILE: '美甲师资料',
|
||||
STAFF_REGISTRATION: '美甲师注册申请',
|
||||
PRODUCT: '作品',
|
||||
EFFECT_DIAGRAM: '效果图',
|
||||
COMMENT: '评论',
|
||||
ORDER_ARTIST_REVIEW: '订单评价',
|
||||
SHOP: '门店资料',
|
||||
ANNOUNCEMENT: '公告',
|
||||
SYSTEM_MESSAGE: '系统消息'
|
||||
}
|
||||
const warnedModerationTypes = new Set<string>()
|
||||
|
||||
function moderationType(type?: string | null) {
|
||||
const key = String(type || '').trim()
|
||||
const label = MODERATION_TYPE_LABELS[key]
|
||||
if (label) return label
|
||||
if (key && !warnedModerationTypes.has(key)) {
|
||||
warnedModerationTypes.add(key)
|
||||
console.warn(`[内容复核] 未映射的内容类型枚举:${key}`)
|
||||
}
|
||||
return '其他'
|
||||
}
|
||||
|
||||
function isUnknownModerationType(type?: string | null) {
|
||||
const key = String(type || '').trim()
|
||||
return !key || !MODERATION_TYPE_LABELS[key]
|
||||
}
|
||||
|
||||
let skipInitialActivationRefresh = true
|
||||
|
||||
@@ -342,12 +342,31 @@
|
||||
<div class="field__control">
|
||||
<a-input v-model:value="moderationForwardTargets[env.key]" :placeholder="`例如 https://${env.key}.example.com/api/integration/wechat/content-moderation/callback`" />
|
||||
</div>
|
||||
<div class="field__control">
|
||||
<span class="control-note">探测顺序(1 最先)</span>
|
||||
<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 / TARGET_MISSING 不自动重试,补齐配置或人工处理后可重放。</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">
|
||||
@@ -356,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>
|
||||
@@ -530,7 +554,10 @@ const moderationSecrets = reactive({ callbackToken: '', encodingAesKey: '' })
|
||||
const clearModerationSecrets = reactive({ callbackToken: false, encodingAesKey: false })
|
||||
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 = [
|
||||
@@ -699,7 +726,17 @@ const load = async () => {
|
||||
moderationForwardTargets.dev = secureConfig.moderationForwardTargets?.dev || ''
|
||||
moderationForwardTargets.sit = secureConfig.moderationForwardTargets?.sit || ''
|
||||
moderationForwardTargets.prod = secureConfig.moderationForwardTargets?.prod || ''
|
||||
const loadedOrder = secureConfig.moderationForwardOrder || []
|
||||
forwardEnvTargets.forEach((env, index) => {
|
||||
const position = loadedOrder.indexOf(env.key)
|
||||
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 = ''
|
||||
@@ -1027,8 +1064,15 @@ const saveModerationConfig = async () => {
|
||||
}
|
||||
|
||||
const forwardStatusLabel = (status?: string) => ({
|
||||
PENDING: '待转发', SUCCESS: '已转发', RETRY: '待重试', FAILED: '失败',
|
||||
NO_ENV: '无法认领', TARGET_MISSING: '目标未配置'
|
||||
CLAIMED: '已认领',
|
||||
PENDING: '待处理',
|
||||
PROCESSING: '处理中',
|
||||
SUCCESS: '已处理',
|
||||
NO_ENV: '无环境认领',
|
||||
FAILED: '失败待重试',
|
||||
DEAD: '已终止',
|
||||
RETRY: '待重试',
|
||||
TARGET_MISSING: '目标未配置'
|
||||
} as Record<string, string>)[status || ''] || '未知'
|
||||
|
||||
const saveModerationForwardConfig = async () => {
|
||||
@@ -1053,8 +1097,13 @@ const saveModerationForwardConfig = async () => {
|
||||
secureStatus.value = await adminSecureIntegrationConfigApi.saveModerationForwardConfig({
|
||||
moderationForwardEnabled: moderationForwardEnabled.value,
|
||||
moderationForwardTargets: { ...moderationForwardTargets },
|
||||
moderationForwardOrder: [...forwardEnvTargets]
|
||||
.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
|
||||
@@ -1336,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; }
|
||||
}
|
||||
|
||||
@@ -22,6 +22,14 @@ module.exports = {
|
||||
})
|
||||
},
|
||||
|
||||
updateColor(userId, color) {
|
||||
return request({
|
||||
url: `/manager/employees/${userId}/color`,
|
||||
method: 'PUT',
|
||||
data: { color }
|
||||
})
|
||||
},
|
||||
|
||||
createUser(data) {
|
||||
return request({
|
||||
url: '/manager/employees/users/unlinked',
|
||||
|
||||
@@ -1,7 +1,22 @@
|
||||
const employeesApi = require('../../api/employees')
|
||||
const { showErrorToast } = require('../../utils/toast')
|
||||
const { markPlanningRefresh } = require('../../utils/planning-refresh')
|
||||
|
||||
const DEFAULT_COLOR = '#247B63'
|
||||
|
||||
function normalizeColor(value) {
|
||||
const raw = String(value || '').trim()
|
||||
if (!raw) return ''
|
||||
const color = raw[0] === '#' ? raw : `#${raw}`
|
||||
return color.toUpperCase()
|
||||
}
|
||||
|
||||
Page({
|
||||
data: {
|
||||
selected: '#247B63',
|
||||
customColor: '#247B63',
|
||||
id: '',
|
||||
saving: false,
|
||||
selected: DEFAULT_COLOR,
|
||||
customColor: DEFAULT_COLOR,
|
||||
wheelColors: [
|
||||
'#E0627A', '#E7785B', '#E2A64B', '#D8C85C', '#9EBB63', '#63B77B',
|
||||
'#4CB7A6', '#56A7D6', '#5F82D7', '#7C70D4', '#A66BC8', '#CF72A8'
|
||||
@@ -15,6 +30,21 @@ Page({
|
||||
'#6D8491', '#829A9A', '#A9B3A2', '#C6B7D1', '#E0C2B6', '#F0D6A8'
|
||||
]
|
||||
},
|
||||
onLoad(options) {
|
||||
this.setData({ id: options && options.id ? options.id : '' })
|
||||
if (this.data.id) {
|
||||
this.loadColor()
|
||||
}
|
||||
},
|
||||
async loadColor() {
|
||||
try {
|
||||
const detail = await employeesApi.detail(this.data.id)
|
||||
const color = normalizeColor(detail && detail.color) || DEFAULT_COLOR
|
||||
this.setData({ selected: color, customColor: color })
|
||||
} catch (error) {
|
||||
showErrorToast(error, '美甲师颜色加载失败')
|
||||
}
|
||||
},
|
||||
select(event) {
|
||||
const color = event.currentTarget.dataset.color
|
||||
this.setData({ selected: color, customColor: color })
|
||||
@@ -27,14 +57,39 @@ Page({
|
||||
this.setData({ customColor: event.detail.value })
|
||||
},
|
||||
applyCustomColor() {
|
||||
let color = (this.data.customColor || '').trim()
|
||||
if (color && color[0] !== '#') color = `#${color}`
|
||||
if (!/^#[0-9a-fA-F]{6}$/.test(color)) {
|
||||
const color = normalizeColor(this.data.customColor)
|
||||
if (!/^#[0-9A-F]{6}$/.test(color)) {
|
||||
wx.showToast({ title: '请输入6位色值', icon: 'none' })
|
||||
return
|
||||
}
|
||||
this.setData({ selected: color.toUpperCase(), customColor: color.toUpperCase() })
|
||||
this.setData({ selected: color, customColor: color })
|
||||
},
|
||||
save() { wx.showToast({ title: '已保存到本地' }) },
|
||||
back() { wx.navigateBack() }
|
||||
async save() {
|
||||
if (this.data.saving) {
|
||||
return
|
||||
}
|
||||
if (!this.data.id) {
|
||||
wx.showToast({ title: '缺少美甲师信息', icon: 'none' })
|
||||
return
|
||||
}
|
||||
const color = normalizeColor(this.data.selected)
|
||||
if (!/^#[0-9A-F]{6}$/.test(color)) {
|
||||
wx.showToast({ title: '请选择颜色', icon: 'none' })
|
||||
return
|
||||
}
|
||||
this.setData({ saving: true })
|
||||
try {
|
||||
const saved = await employeesApi.updateColor(this.data.id, color)
|
||||
const savedColor = normalizeColor(saved && saved.color) || color
|
||||
this.setData({ selected: savedColor, customColor: savedColor, saving: false })
|
||||
markPlanningRefresh()
|
||||
wx.showToast({ title: '颜色已保存', icon: 'success' })
|
||||
} catch (error) {
|
||||
this.setData({ saving: false })
|
||||
showErrorToast(error, '颜色保存失败')
|
||||
}
|
||||
},
|
||||
back() {
|
||||
wx.navigateBack()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
const assert = require('assert')
|
||||
const employeesApi = require('../../api/employees')
|
||||
|
||||
const storage = {}
|
||||
const app = { globalData: {} }
|
||||
const toasts = []
|
||||
global.wx = {
|
||||
getAccountInfoSync: () => ({ miniProgram: { envVersion: 'develop' } }),
|
||||
getDeviceInfo: () => ({ platform: 'devtools' }),
|
||||
showToast: options => toasts.push(options),
|
||||
navigateBack: () => {},
|
||||
setStorageSync: (key, value) => { storage[key] = value },
|
||||
getStorageSync: key => storage[key]
|
||||
}
|
||||
global.getApp = () => app
|
||||
global.getCurrentPages = () => []
|
||||
|
||||
let definition
|
||||
global.Page = value => { definition = value }
|
||||
require('./index')
|
||||
|
||||
const page = {
|
||||
...definition,
|
||||
data: JSON.parse(JSON.stringify(definition.data)),
|
||||
setData(values) {
|
||||
Object.entries(values).forEach(([key, value]) => {
|
||||
const parts = key.split('.')
|
||||
let target = this.data
|
||||
for (let index = 0; index < parts.length - 1; index += 1) target = target[parts[index]]
|
||||
target[parts[parts.length - 1]] = value
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function run() {
|
||||
page.setData({ id: '88' })
|
||||
employeesApi.detail = async () => ({ color: '#8fb89a' })
|
||||
await page.loadColor()
|
||||
assert.strictEqual(page.data.selected, '#8FB89A')
|
||||
assert.strictEqual(page.data.customColor, '#8FB89A')
|
||||
|
||||
page.setData({ selected: '#aabbcc', customColor: '#aabbcc' })
|
||||
let saved
|
||||
employeesApi.updateColor = async (id, color) => {
|
||||
saved = { id, color }
|
||||
return { color: '#AABBCC' }
|
||||
}
|
||||
await page.save()
|
||||
assert.deepStrictEqual(saved, { id: '88', color: '#AABBCC' })
|
||||
assert.strictEqual(page.data.selected, '#AABBCC')
|
||||
assert.strictEqual(page.data.saving, false)
|
||||
assert.strictEqual(app.globalData.planningNeedRefresh, true)
|
||||
assert.strictEqual(storage.planningNeedRefresh, '1')
|
||||
assert.strictEqual(toasts[toasts.length - 1].title, '颜色已保存')
|
||||
|
||||
app.globalData.planningNeedRefresh = false
|
||||
storage.planningNeedRefresh = ''
|
||||
employeesApi.updateColor = async () => {
|
||||
throw new Error('颜色保存失败,请稍后重试')
|
||||
}
|
||||
await page.save()
|
||||
assert.strictEqual(page.data.saving, false)
|
||||
assert.strictEqual(app.globalData.planningNeedRefresh, false)
|
||||
assert.strictEqual(toasts[toasts.length - 1].title, '颜色保存失败,请稍后重试')
|
||||
}
|
||||
|
||||
run().catch(error => {
|
||||
console.error(error)
|
||||
process.exitCode = 1
|
||||
})
|
||||
@@ -18,7 +18,12 @@ Page({
|
||||
|
||||
onLoad(options) {
|
||||
this.setData({ id: options.id || '' })
|
||||
this.loadDetail()
|
||||
},
|
||||
|
||||
onShow() {
|
||||
if (this.data.id) {
|
||||
this.loadDetail()
|
||||
}
|
||||
},
|
||||
|
||||
async loadDetail() {
|
||||
|
||||
Reference in New Issue
Block a user