完善审核来源标识与图片读取设置
自动发布开发环境 Nacos 配置 / publish (push) Successful in 18s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 6s

This commit is contained in:
2026-11-03 17:57:12 +08:00
parent 19e2cd2594
commit c626a1e6d6
24 changed files with 530 additions and 27 deletions
@@ -9,6 +9,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.entity.ObjectStorageReplic
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageOrchestrationService;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageProvider;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageReplicaService;
import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@@ -23,6 +24,9 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@@ -35,6 +39,12 @@ public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrche
private final List<ObjectStorageProvider> providers;
private final ObjectStorageProperties objectStorageProperties;
private final ObjectStorageReplicaService objectStorageReplicaService;
private final SystemParameterConfigService systemParameterConfigService;
private volatile ProviderOrderCache providerOrderCache;
private static final long PROVIDER_ORDER_CACHE_MILLIS = 30_000L;
private static final String PROVIDER_ORDER_GROUP = "FILE";
private static final String PROVIDER_ORDER_KEY = "IMAGE_READ_PROVIDER_ORDER";
private static final Set<String> SUPPORTED_PROVIDERS = Set.of("MINIO", "QINIU_KODO", "ALIYUN_OSS");
@Override
public ObjectStorageUploadOutcome uploadPrimary(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception {
@@ -110,7 +120,7 @@ public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrche
Map<String, ObjectStorageReplicaDO> replicaMap = replicas.stream()
.collect(Collectors.toMap(ObjectStorageReplicaDO::getProvider, replica -> replica, (left, right) -> left, LinkedHashMap::new));
Exception lastFailure = null;
for (String providerCode : objectStorageProperties.getProviderOrder()) {
for (String providerCode : readProviderOrder()) {
ObjectStorageReplicaDO replica = replicaMap.get(providerCode);
if (replica == null
|| !Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(replica.getUploadStatus())) {
@@ -129,7 +139,7 @@ public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrche
@Override
public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) {
Exception lastFailure = null;
for (String providerCode : objectStorageProperties.getProviderOrder()) {
for (String providerCode : readProviderOrder()) {
try {
ObjectStorageProvider provider = requireProvider(providerCode);
ensureEnabled(provider);
@@ -142,6 +152,52 @@ public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrche
throw new IllegalStateException("No available object storage signed URL for objectName=" + objectName, lastFailure);
}
private List<String> readProviderOrder() {
long now = System.currentTimeMillis();
ProviderOrderCache cache = providerOrderCache;
if (cache != null && now < cache.expiresAt) return cache.providers;
synchronized (this) {
cache = providerOrderCache;
now = System.currentTimeMillis();
if (cache != null && now < cache.expiresAt) return cache.providers;
List<String> providers;
try {
providers = parseProviderOrder(systemParameterConfigService.getEnabledValue(PROVIDER_ORDER_GROUP, PROVIDER_ORDER_KEY));
} catch (RuntimeException exception) {
log.warn("读取对象存储签名访问顺序失败,回退到当前环境默认配置", exception);
providers = Collections.emptyList();
}
if (providers.isEmpty()) providers = validateFallbackOrder(objectStorageProperties.getProviderOrder());
providerOrderCache = new ProviderOrderCache(providers, now + PROVIDER_ORDER_CACHE_MILLIS);
return providers;
}
}
private List<String> parseProviderOrder(String value) {
if (!StringUtils.hasText(value)) return Collections.emptyList();
return validateFallbackOrder(Arrays.asList(value.split(",")));
}
private List<String> validateFallbackOrder(List<String> configured) {
if (configured == null) return Collections.emptyList();
List<String> providers = configured.stream().filter(StringUtils::hasText)
.map(value -> value.trim().toUpperCase(java.util.Locale.ROOT)).collect(Collectors.toList());
if (providers.size() != SUPPORTED_PROVIDERS.size() || !SUPPORTED_PROVIDERS.equals(new java.util.HashSet<>(providers))) {
return Collections.emptyList();
}
return Collections.unmodifiableList(providers);
}
private static final class ProviderOrderCache {
private final List<String> providers;
private final long expiresAt;
private ProviderOrderCache(List<String> providers, long expiresAt) {
this.providers = providers;
this.expiresAt = expiresAt;
}
}
private boolean uploadReplica(ObjectStorageFileDO file, String providerCode, Map<String, ObjectStorageReplicaDO> replicaMap) {
ObjectStorageReplicaDTO replicaDTO = new ObjectStorageReplicaDTO();
replicaDTO.setProvider(providerCode);
@@ -72,10 +72,12 @@ public class WechatContentModerationCallbackController {
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");
@@ -83,12 +85,23 @@ public class WechatContentModerationCallbackController {
if (!StringUtils.hasText(suggest)) suggest = "review";
reason = firstText(root, "errmsg", "reason");
if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调";
extra = firstText(root, "extra", "Extra");
}
if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("微信审核回调缺少任务标识");
contentModerationService.handleWechatImageResult(taskId, suggest, reason);
contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra));
return "success";
}
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 extractEncryptedPayload(String body) throws Exception {
if (!StringUtils.hasText(body)) {
throw new IllegalArgumentException("微信审核回调消息体为空");
@@ -17,6 +17,7 @@ public class ContentModerationImageTaskDO extends BaseEntity {
private Long id;
private Long recordId;
private Long fileId;
private String sourceEnvVersion;
private String providerTaskId;
private String status;
private String resultCode;
@@ -6,4 +6,8 @@ public interface ContentModerationProvider {
ModerationOutcome reviewText(String contentType, String content, String openId);
ModerationOutcome submitImage(String contentType, String imageUrl, String openId);
default ModerationOutcome submitImage(String contentType, String imageUrl, String openId, String sourceEnvVersion) {
return submitImage(contentType, imageUrl, openId);
}
}
@@ -32,6 +32,11 @@ public class RoutingContentModerationProvider implements ContentModerationProvid
return resolveProvider().submitImage(contentType, imageUrl, openId);
}
@Override
public ModerationOutcome submitImage(String contentType, String imageUrl, String openId, String sourceEnvVersion) {
return resolveProvider().submitImage(contentType, imageUrl, openId, sourceEnvVersion);
}
private ContentModerationProvider resolveProvider() {
try {
ModerationRuntimeConfig config = secureIntegrationConfigService.getModerationRuntimeConfig();
@@ -57,6 +57,11 @@ 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) {
if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核");
if (!StringUtils.hasText(imageUrl) || !imageUrl.startsWith("https://")) {
return retry("IMAGE_URL_INVALID", "审核图片需要短期有效的 HTTPS 地址");
@@ -67,9 +72,22 @@ public class WechatContentModerationProvider implements ContentModerationProvide
payload.put("version", 2);
payload.put("scene", properties.getScene());
payload.put("openid", openId);
payload.put("extra", encodeSourceEnvVersion(sourceEnvVersion));
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";
}
try {
return objectMapper.writeValueAsString(Map.of("envVersion", envVersion));
} catch (java.io.IOException exception) {
throw new IllegalStateException("无法编码微信审核来源版本", exception);
}
}
private Map<String, Object> post(String endpoint, Map<String, Object> payload) {
String url = UriComponentsBuilder.fromHttpUrl(endpoint)
.queryParam("access_token", wechatMiniClientService.getAccessTokenForContentModeration())
@@ -12,6 +12,10 @@ 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);
boolean handleWechatImageResult(String providerTaskId, String suggest, String reason, String sourceEnvVersion);
default boolean handleWechatImageResult(String providerTaskId, String suggest, String reason) {
return handleWechatImageResult(providerTaskId, suggest, reason, null);
}
int retryFailedImageTasks();
}
@@ -42,6 +42,8 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.time.LocalDateTime;
import java.util.ArrayList;
@@ -116,9 +118,11 @@ public class ContentModerationServiceImpl implements ContentModerationService {
ContentModerationImageTaskDO task = new ContentModerationImageTaskDO();
task.setRecordId(record.getId());
task.setFileId(fileId);
String sourceEnvVersion = currentMiniProgramEnvVersion();
task.setSourceEnvVersion(sourceEnvVersion);
task.setAttemptCount(1);
ModerationOutcome imageOutcome = StringUtils.hasText(openId)
? safeImageReview(contentType, fileId, openId)
? safeImageReview(contentType, fileId, openId, sourceEnvVersion)
: outcome(ModerationOutcome.Status.PENDING, "OPENID_REQUIRED", "发布者未绑定可核验的微信身份,转人工复核");
boolean imageRetryExhausted = exhausted(imageOutcome, 1, maxRetries);
task.setStatus(imageRetryExhausted ? "PENDING" : imageOutcome.status().name());
@@ -201,6 +205,12 @@ 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"));
@@ -215,6 +225,13 @@ 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");
@@ -253,7 +270,10 @@ public class ContentModerationServiceImpl implements ContentModerationService {
if (task == null) continue;
attempted++;
task.setProviderTaskId(null);
ModerationOutcome outcome = safeImageReview(record.getContentType(), task.getFileId(), openId);
String sourceEnvVersion = normalizeTaskEnvVersion(task.getSourceEnvVersion());
if ("LEGACY".equals(sourceEnvVersion)) sourceEnvVersion = "UNKNOWN";
task.setSourceEnvVersion(sourceEnvVersion);
ModerationOutcome outcome = safeImageReview(record.getContentType(), task.getFileId(), openId, sourceEnvVersion);
task.setAttemptCount((task.getAttemptCount() == null ? 0 : task.getAttemptCount()) + 1);
task.setStatus(exhausted(outcome, task.getAttemptCount(), maxRetries) ? "PENDING" : outcome.status().name());
task.setResultCode(outcome.code());
@@ -500,15 +520,32 @@ public class ContentModerationServiceImpl implements ContentModerationService {
catch (RuntimeException exception) { return outcome(ModerationOutcome.Status.RETRY, "PROVIDER_FAILURE", "内容审核服务暂不可用,内容已隔离等待重试"); }
}
private ModerationOutcome safeImageReview(String type, Long fileId, String openId) {
private ModerationOutcome safeImageReview(String type, Long fileId, String openId, String sourceEnvVersion) {
try {
String url = objectStorageFileService.createTemporaryModerationUrl(fileId, properties.getImageUrlExpireMinutes());
return provider.submitImage(type, url, openId);
return provider.submitImage(type, url, openId, normalizeEnvVersion(sourceEnvVersion));
} catch (RuntimeException exception) {
return outcome(ModerationOutcome.Status.RETRY, "IMAGE_REVIEW_FAILURE", "图片审核暂不可用,内容已隔离等待重试");
}
}
private String currentMiniProgramEnvVersion() {
Object attributes = RequestContextHolder.getRequestAttributes();
if (!(attributes instanceof ServletRequestAttributes)) return "UNKNOWN";
String envVersion = ((ServletRequestAttributes) attributes).getRequest().getHeader("X-Mini-Program-Env-Version");
return normalizeEnvVersion(envVersion);
}
private String normalizeEnvVersion(String value) {
if ("develop".equals(value) || "trial".equals(value) || "release".equals(value)) return value;
if ("LEGACY".equals(value)) return "LEGACY";
return "UNKNOWN";
}
private String normalizeTaskEnvVersion(String value) {
return StringUtils.hasText(value) ? normalizeEnvVersion(value) : "LEGACY";
}
private String resolveOpenId(Long userId) {
if (userId == null) return null;
try {
@@ -26,6 +26,9 @@ import java.util.stream.Collectors;
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class SystemParameterConfigServiceImpl implements SystemParameterConfigService {
private static final String STORAGE_READ_ORDER_GROUP = "FILE";
private static final String STORAGE_READ_ORDER_KEY = "IMAGE_READ_PROVIDER_ORDER";
private static final java.util.Set<String> STORAGE_PROVIDERS = java.util.Set.of("MINIO", "QINIU_KODO", "ALIYUN_OSS");
/**
* Purpose: configMapper supports SystemParameterConfigServiceImpl.java by holding or executing the config mapper business role.
@@ -69,6 +72,12 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe
if ("MAP".equals(group)) {
throw new IllegalArgumentException("地图密钥已迁移至安全接入配置,不允许通过通用参数接口读写");
}
if (STORAGE_READ_ORDER_KEY.equals(key)) {
if (!STORAGE_READ_ORDER_GROUP.equals(group)) {
throw new IllegalArgumentException("对象存储读取顺序只能保存在 FILE 配置分组");
}
validateStorageReadOrder(dto.getConfigValue());
}
if (AdminDefaultPasswordSupport.isDefaultPasswordConfig(group, key)) {
AdminDefaultPasswordSupport.validateDefaultPassword(dto.getConfigValue());
}
@@ -135,6 +144,14 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe
return value.trim().toUpperCase(Locale.ROOT);
}
private void validateStorageReadOrder(String value) {
List<String> providers = value == null ? Collections.emptyList() : java.util.Arrays.stream(value.split(","))
.map(String::trim).map(item -> item.toUpperCase(Locale.ROOT)).collect(Collectors.toList());
if (providers.size() != STORAGE_PROVIDERS.size() || !STORAGE_PROVIDERS.equals(new java.util.HashSet<>(providers))) {
throw new IllegalArgumentException("对象存储读取顺序必须且仅能包含 MinIO、七牛云、阿里云 OSS 各一次");
}
}
/**
* Purpose: toVO supports SystemParameterConfigServiceImpl.java by holding or executing the to vo business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
@@ -0,0 +1,31 @@
SET @column_exists = (
SELECT COUNT(1)
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 't_content_moderation_image_task'
AND column_name = 'source_env_version'
);
SET @migration_sql = IF(
@column_exists = 0,
'ALTER TABLE t_content_moderation_image_task ADD COLUMN source_env_version VARCHAR(20) NOT NULL DEFAULT ''LEGACY'' COMMENT ''小程序来源环境:develop/trial/release/UNKNOWN;历史任务为LEGACY'' AFTER file_id',
'SELECT 1'
);
PREPARE migration_statement FROM @migration_sql;
EXECUTE migration_statement;
DEALLOCATE PREPARE migration_statement;
INSERT INTO t_system_parameter_config (
id, config_group, config_key, config_name, config_value, enabled, remark,
create_time, update_time, is_delete
)
VALUES (
313931273555139021, 'FILE', 'IMAGE_READ_PROVIDER_ORDER', '对象存储图片读取优先级',
'MINIO,QINIU_KODO,ALIYUN_OSS', 1,
'仅作用于签名访问 URL 生成和可用副本回退;不影响上传和副本修复顺序',
NOW(), NOW(), 0
)
ON DUPLICATE KEY UPDATE
config_name = VALUES(config_name),
remark = VALUES(remark),
is_delete = 0,
update_time = NOW();
@@ -0,0 +1,126 @@
package com.xiaowang.jayucloud.salon.core.modules.file.service.impl;
import com.xiaowang.jayucloud.salon.core.config.ObjectStorageProperties;
import com.xiaowang.jayucloud.salon.core.modules.file.entity.ObjectStorageFileDO;
import com.xiaowang.jayucloud.salon.core.modules.file.entity.ObjectStorageReplicaDO;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageProvider;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageReplicaService;
import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ObjectStorageOrchestrationServiceImplTest {
@Test
void savedOrderControlsSignedUrlsButNotUploadPreference() throws Exception {
ObjectStorageProvider minio = provider("MINIO", "minio");
ObjectStorageProvider qiniu = provider("QINIU_KODO", "qiniu");
ObjectStorageProvider oss = provider("ALIYUN_OSS", "oss");
ObjectStorageProperties properties = new ObjectStorageProperties();
properties.setProviderOrder(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"));
properties.setReplicaRequiredProviders(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"));
ObjectStorageReplicaService replicaService = mock(ObjectStorageReplicaService.class);
ObjectStorageReplicaDO minioReplica = replica("MINIO");
ObjectStorageReplicaDO qiniuReplica = replica("QINIU_KODO");
ObjectStorageReplicaDO ossReplica = replica("ALIYUN_OSS");
when(replicaService.listByFileId(7L)).thenReturn(List.of(minioReplica, qiniuReplica, ossReplica));
SystemParameterConfigService configService = mock(SystemParameterConfigService.class);
when(configService.getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER"))
.thenReturn("ALIYUN_OSS,QINIU_KODO,MINIO");
ObjectStorageOrchestrationServiceImpl service = new ObjectStorageOrchestrationServiceImpl(
List.of(minio, qiniu, oss), properties, replicaService, configService);
assertEquals("oss:signed", service.getPresignedUrl(7L, "object", 5));
service.uploadPrimary(new ByteArrayInputStream(new byte[] {1}), 1, "image/png", "object");
verify(oss).getPresignedUrl("oss-object", 5);
verify(minio, never()).getPresignedUrl(any(), any());
verify(minio).uploadStream(any(InputStream.class), eq(1L), eq("image/png"), eq("object"));
verify(configService).getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER");
}
@Test
void signedUrlFallsBackToNextConfiguredReadableReplica() throws Exception {
ObjectStorageProvider minio = provider("MINIO", "minio");
ObjectStorageProvider qiniu = provider("QINIU_KODO", "qiniu");
ObjectStorageProvider oss = provider("ALIYUN_OSS", "oss");
when(oss.getPresignedUrl("oss-object", 5)).thenThrow(new IllegalStateException("OSS unavailable"));
when(qiniu.getPresignedUrl("qiniu_kodo-object", 5)).thenReturn("qiniu:signed");
ObjectStorageProperties properties = new ObjectStorageProperties();
properties.setProviderOrder(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"));
ObjectStorageReplicaService replicaService = mock(ObjectStorageReplicaService.class);
when(replicaService.listByFileId(8L)).thenReturn(List.of(
replica("MINIO"), replica("QINIU_KODO"), replica("ALIYUN_OSS")));
SystemParameterConfigService configService = mock(SystemParameterConfigService.class);
when(configService.getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER"))
.thenReturn("ALIYUN_OSS,QINIU_KODO,MINIO");
ObjectStorageOrchestrationServiceImpl service = new ObjectStorageOrchestrationServiceImpl(
List.of(minio, qiniu, oss), properties, replicaService, configService);
assertEquals("qiniu:signed", service.getPresignedUrl(8L, "object", 5));
org.mockito.InOrder providerOrder = inOrder(oss, qiniu);
providerOrder.verify(oss).getPresignedUrl("oss-object", 5);
providerOrder.verify(qiniu).getPresignedUrl("qiniu_kodo-object", 5);
verify(minio, never()).getPresignedUrl(any(), any());
}
@Test
void replicaRepairKeepsEnvironmentSourceReadOrder() throws Exception {
ObjectStorageProvider minio = provider("MINIO", "minio");
ObjectStorageProvider qiniu = provider("QINIU_KODO", "qiniu");
ObjectStorageProvider oss = provider("ALIYUN_OSS", "oss");
when(minio.downloadFile("minio-object")).thenReturn(new ByteArrayInputStream(new byte[] {1}));
ObjectStorageProperties properties = new ObjectStorageProperties();
properties.setProviderOrder(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"));
properties.setReplicaRequiredProviders(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"));
ObjectStorageReplicaService replicaService = mock(ObjectStorageReplicaService.class);
when(replicaService.listByFileId(9L)).thenReturn(List.of(replica("MINIO"), replica("QINIU_KODO")));
SystemParameterConfigService configService = mock(SystemParameterConfigService.class);
when(configService.getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER"))
.thenReturn("ALIYUN_OSS,QINIU_KODO,MINIO");
ObjectStorageOrchestrationServiceImpl service = new ObjectStorageOrchestrationServiceImpl(
List.of(minio, qiniu, oss), properties, replicaService, configService);
ObjectStorageFileDO file = new ObjectStorageFileDO();
file.setId(9L);
file.setObjectName("object");
file.setFileSize(1L);
file.setContentType("image/png");
service.completeReplicas(file);
verify(minio).downloadFile("minio-object");
verify(qiniu, never()).downloadFile(any());
verify(oss).uploadStream(any(InputStream.class), eq(1L), eq("image/png"), eq("object"));
verify(configService, never()).getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER");
}
private ObjectStorageProvider provider(String code, String name) throws Exception {
ObjectStorageProvider provider = mock(ObjectStorageProvider.class);
when(provider.providerCode()).thenReturn(code);
when(provider.isEnabled()).thenReturn(true);
when(provider.getPresignedUrl("oss-object", 5)).thenReturn("oss:signed");
when(provider.uploadStream(any(InputStream.class), anyLong(), any(), any())).thenReturn(name + ":uploaded");
return provider;
}
private ObjectStorageReplicaDO replica(String code) {
ObjectStorageReplicaDO replica = new ObjectStorageReplicaDO();
replica.setProvider(code);
replica.setObjectName(code.equals("ALIYUN_OSS") ? "oss-object" : code.toLowerCase() + "-object");
replica.setUploadStatus(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED);
return replica;
}
}
@@ -72,7 +72,7 @@ class WechatContentModerationCallbackControllerTest {
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\"}}");
.thenReturn("{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"},\"extra\":\"{\\\"envVersion\\\":\\\"trial\\\"}\"}");
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService)).build();
mvc.perform(post("/integration/wechat/content-moderation/callback")
@@ -86,7 +86,7 @@ class WechatContentModerationCallbackControllerTest {
.andExpect(content().string("success"));
verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature");
verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调");
verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial");
}
@Test
@@ -98,8 +98,11 @@ class WechatContentModerationCallbackControllerTest {
when(crypto.encryptedValue(xml)).thenReturn("encrypted-xml");
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature"))
.thenReturn(true);
when(crypto.decrypt("encrypted-xml", "encoding-aes-key", "mini-app-id"))
.thenReturn("{\"trace_id\":\"task-xml\",\"result\":{\"suggest\":\"review\"}}");
String decodedXml = "<xml><trace_id>task-xml</trace_id><suggest>review</suggest><extra>{&quot;envVersion&quot;:&quot;release&quot;}</extra></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("{\"envVersion\":\"release\"}");
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService)).build();
mvc.perform(post("/integration/wechat/content-moderation/callback")
@@ -113,7 +116,7 @@ class WechatContentModerationCallbackControllerTest {
.andExpect(content().string("success"));
verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature");
verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调");
verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调", "release");
}
private SecureIntegrationConfigService readyWechatConfig() {
@@ -0,0 +1,56 @@
package com.xiaowang.jayucloud.salon.core.modules.system.service.impl;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService;
import com.xiaowang.jayucloud.salon.core.modules.system.dto.SystemParameterConfigDTO;
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SystemParameterConfigMapper;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class SystemParameterConfigServiceImplTest {
@Test
void objectStorageReadOrderMustContainEachProviderExactlyOnce() {
SystemParameterConfigMapper mapper = mock(SystemParameterConfigMapper.class);
SystemParameterConfigServiceImpl service = new SystemParameterConfigServiceImpl(
mapper, mock(MessageHubPushConfigService.class));
UserDO admin = new UserDO();
admin.setType(4);
SystemParameterConfigDTO config = new SystemParameterConfigDTO();
config.setConfigGroup("FILE");
config.setConfigKey("IMAGE_READ_PROVIDER_ORDER");
config.setConfigName("对象存储图片读取优先级");
config.setConfigValue("MINIO,MINIO,ALIYUN_OSS");
assertThrows(IllegalArgumentException.class, () -> service.saveConfig(admin, config));
verify(mapper, never()).selectOne(any());
verify(mapper, never()).insert(any());
}
@Test
void validObjectStorageReadOrderIsSavedAsProvided() {
SystemParameterConfigMapper mapper = mock(SystemParameterConfigMapper.class);
when(mapper.selectOne(any())).thenReturn(null);
SystemParameterConfigServiceImpl service = new SystemParameterConfigServiceImpl(
mapper, mock(MessageHubPushConfigService.class));
UserDO admin = new UserDO();
admin.setType(4);
SystemParameterConfigDTO config = new SystemParameterConfigDTO();
config.setConfigGroup("FILE");
config.setConfigKey("IMAGE_READ_PROVIDER_ORDER");
config.setConfigName("对象存储图片读取优先级");
config.setConfigValue("ALIYUN_OSS,QINIU_KODO,MINIO");
service.saveConfig(admin, config);
org.mockito.ArgumentCaptor<com.xiaowang.jayucloud.salon.core.modules.system.entity.SystemParameterConfigDO> captor =
org.mockito.ArgumentCaptor.forClass(com.xiaowang.jayucloud.salon.core.modules.system.entity.SystemParameterConfigDO.class);
verify(mapper).insert(captor.capture());
org.junit.jupiter.api.Assertions.assertEquals("ALIYUN_OSS,QINIU_KODO,MINIO", captor.getValue().getConfigValue());
}
}