|
|
@@ -1,7 +1,19 @@
|
|
|
package com.etotem.cfc.service;
|
|
|
|
|
|
+import com.etotem.cfc.config.AiYunyiProperties;
|
|
|
+import org.slf4j.Logger;
|
|
|
+import org.slf4j.LoggerFactory;
|
|
|
+import org.springframework.http.HttpEntity;
|
|
|
+import org.springframework.http.HttpHeaders;
|
|
|
+import org.springframework.http.HttpMethod;
|
|
|
+import org.springframework.http.MediaType;
|
|
|
+import org.springframework.http.ResponseEntity;
|
|
|
+import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
|
|
import org.springframework.stereotype.Service;
|
|
|
+import org.springframework.web.client.RestClientException;
|
|
|
+import org.springframework.web.client.RestTemplate;
|
|
|
|
|
|
+import java.lang.reflect.Array;
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
import java.security.KeyFactory;
|
|
|
import java.security.PrivateKey;
|
|
|
@@ -10,9 +22,14 @@ import java.security.Signature;
|
|
|
import java.security.spec.PKCS8EncodedKeySpec;
|
|
|
import java.security.spec.X509EncodedKeySpec;
|
|
|
import java.util.Base64;
|
|
|
+import java.util.Collection;
|
|
|
import java.util.LinkedHashMap;
|
|
|
import java.util.Map;
|
|
|
+import java.util.concurrent.atomic.AtomicInteger;
|
|
|
+import java.util.concurrent.atomic.AtomicLong;
|
|
|
|
|
|
+import javax.annotation.PostConstruct;
|
|
|
+import javax.annotation.Resource;
|
|
|
import javax.crypto.Cipher;
|
|
|
|
|
|
/**
|
|
|
@@ -145,4 +162,207 @@ public class AicdsGatewayService {
|
|
|
throw new IllegalArgumentException("爱云医密钥 PEM 格式非法(Base64 解码失败)", e);
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+ // ==================== 网关能力(ai.aiyunyi.gateway,S-cfc-471) ====================
|
|
|
+
|
|
|
+ private static final Logger log = LoggerFactory.getLogger(AicdsGatewayService.class);
|
|
|
+
|
|
|
+ /** 连接超时默认值(毫秒,>0),无 Spring 上下文/未绑定配置时保证 init() 仍可设置有效超时。 */
|
|
|
+ private static final int DEFAULT_CONNECT_TIMEOUT_MS = 5000;
|
|
|
+ /** 读取超时默认值(毫秒,>0),爱云医 AI 检测接口耗时较长。 */
|
|
|
+ private static final int DEFAULT_READ_TIMEOUT_MS = 15000;
|
|
|
+ /** 连续失败多少次后打开熔断。 */
|
|
|
+ private static final int DEFAULT_FAILURE_THRESHOLD = 3;
|
|
|
+ /** 熔断后多久允许半开(毫秒)。 */
|
|
|
+ private static final long DEFAULT_RESET_TIMEOUT_MS = 30000L;
|
|
|
+
|
|
|
+ /** 未配置鉴权密钥时的占位头值前缀(仅用于保证头部契约存在,不可用于真实鉴权)。 */
|
|
|
+ private static final String PLACEHOLDER_SIGN_PREFIX = "placeholder-sign-";
|
|
|
+ private static final String PLACEHOLDER_USER_PREFIX = "placeholder-user-";
|
|
|
+
|
|
|
+ /** 配置(Spring 环境由容器注入;反射构造时为 null,走默认值)。 */
|
|
|
+ @Resource
|
|
|
+ private AiYunyiProperties aiYunyiProperties;
|
|
|
+
|
|
|
+ /** RestTemplate 非 final:便于单测用 Mockito mock 替换并断言请求头(AC5)。 */
|
|
|
+ private RestTemplate restTemplate = new RestTemplate();
|
|
|
+
|
|
|
+ private int timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS;
|
|
|
+ private int readTimeoutMs = DEFAULT_READ_TIMEOUT_MS;
|
|
|
+ private int failureThreshold = DEFAULT_FAILURE_THRESHOLD;
|
|
|
+ private long resetTimeoutMs = DEFAULT_RESET_TIMEOUT_MS;
|
|
|
+
|
|
|
+ /** 熔断状态(仿 AiGateway,AC7)。 */
|
|
|
+ private final AtomicInteger consecutiveFailures = new AtomicInteger(0);
|
|
|
+ private final AtomicLong lastFailureTime = new AtomicLong(0);
|
|
|
+ private volatile boolean circuitOpen = false;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * AC6:为 RestTemplate 应用连接/读取超时(仿 AiGateway#init)。
|
|
|
+ * 由 Spring @PostConstruct 调用;单测中反射调用同样生效。
|
|
|
+ */
|
|
|
+ @PostConstruct
|
|
|
+ public void init() {
|
|
|
+ if (aiYunyiProperties != null) {
|
|
|
+ if (aiYunyiProperties.getTimeoutMs() > 0) {
|
|
|
+ this.timeoutMs = aiYunyiProperties.getTimeoutMs();
|
|
|
+ }
|
|
|
+ if (aiYunyiProperties.getReadTimeoutMs() > 0) {
|
|
|
+ this.readTimeoutMs = aiYunyiProperties.getReadTimeoutMs();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
|
|
+ factory.setConnectTimeout(timeoutMs);
|
|
|
+ factory.setReadTimeout(readTimeoutMs);
|
|
|
+ restTemplate.setRequestFactory(factory);
|
|
|
+ log.info("AicdsGatewayService 已初始化: connectTimeout={}ms, readTimeout={}ms",
|
|
|
+ timeoutMs, readTimeoutMs);
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 供单测注入 mock RestTemplate。 */
|
|
|
+ public void setRestTemplate(RestTemplate restTemplate) {
|
|
|
+ this.restTemplate = restTemplate;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * AC8:统一调用入口,走 {@link RestTemplate#exchange(String, HttpMethod, HttpEntity, Class, Object...)}。
|
|
|
+ * accessToken/userId 传 null 表示登录类调用(不带业务头)。
|
|
|
+ */
|
|
|
+ public <T> ResponseEntity<T> exchange(String path, Object body, Class<T> responseType,
|
|
|
+ String accessToken, String userId) {
|
|
|
+ if (isCircuitOpen()) {
|
|
|
+ throw new IllegalStateException("爱云医网关熔断中,拒绝发起请求: " + path);
|
|
|
+ }
|
|
|
+ HttpHeaders headers = buildGatewayHeaders(accessToken, userId);
|
|
|
+ HttpEntity<Object> entity = new HttpEntity<Object>(body, headers);
|
|
|
+ String url = resolveBaseUrl() + (path == null ? "" : path);
|
|
|
+ try {
|
|
|
+ ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, entity,
|
|
|
+ responseType, new Object[0]);
|
|
|
+ consecutiveFailures.set(0);
|
|
|
+ return response;
|
|
|
+ } catch (RestClientException e) {
|
|
|
+ recordFailure();
|
|
|
+ throw e;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * AC9/AC10:构造每次调用的鉴权头。
|
|
|
+ * <ul>
|
|
|
+ * <li>登录调用:X-App-Key / X-Timestamp / X-Api-Sign;</li>
|
|
|
+ * <li>业务调用:额外 Authorization(Bearer) 与 X-User-Id-Encrypt。</li>
|
|
|
+ * </ul>
|
|
|
+ * 未配置密钥时不静默产出空串,而是用非空占位值维持头部契约;真实调用须配置
|
|
|
+ * aiyunyi.private-key / aiyunyi.public-key 才会走 SHA256withRSA 真签名/RSA 加密。
|
|
|
+ */
|
|
|
+ private HttpHeaders buildGatewayHeaders(String accessToken, String userId) {
|
|
|
+ HttpHeaders headers = new HttpHeaders();
|
|
|
+ headers.setContentType(MediaType.APPLICATION_JSON);
|
|
|
+
|
|
|
+ String appKey = resolveAppKey();
|
|
|
+ String timestamp = String.valueOf(System.currentTimeMillis());
|
|
|
+ headers.set(H_APP_KEY, appKey);
|
|
|
+ headers.set(H_TIMESTAMP, timestamp);
|
|
|
+ headers.set(H_API_SIGN, resolveSign(appKey, timestamp));
|
|
|
+
|
|
|
+ boolean businessCall = accessToken != null && userId != null;
|
|
|
+ if (businessCall) {
|
|
|
+ headers.set(H_AUTHORIZATION, "Bearer " + accessToken);
|
|
|
+ headers.set(H_USER_ID_ENCRYPT, resolveEncryptedUserId(userId));
|
|
|
+ }
|
|
|
+ return headers;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String resolveAppKey() {
|
|
|
+ String appKey = aiYunyiProperties == null ? null : aiYunyiProperties.getAppKey();
|
|
|
+ return isBlank(appKey) ? AiYunyiProperties.DEFAULT_APP_KEY : appKey;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String resolveBaseUrl() {
|
|
|
+ String baseUrl = aiYunyiProperties == null ? null : aiYunyiProperties.getBaseUrl();
|
|
|
+ return isBlank(baseUrl) ? AiYunyiProperties.DEFAULT_BASE_URL : baseUrl;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String resolveSign(String appKey, String timestamp) {
|
|
|
+ String privateKey = aiYunyiProperties == null ? null : aiYunyiProperties.getPrivateKey();
|
|
|
+ if (isBlank(privateKey)) {
|
|
|
+ return PLACEHOLDER_SIGN_PREFIX + appKey + "-" + timestamp;
|
|
|
+ }
|
|
|
+ return sign(buildSignString(appKey, Long.parseLong(timestamp)), privateKey);
|
|
|
+ }
|
|
|
+
|
|
|
+ private String resolveEncryptedUserId(String userId) {
|
|
|
+ String publicKey = aiYunyiProperties == null ? null : aiYunyiProperties.getPublicKey();
|
|
|
+ if (isBlank(publicKey)) {
|
|
|
+ return PLACEHOLDER_USER_PREFIX + Base64.getEncoder()
|
|
|
+ .encodeToString(userId.getBytes(StandardCharsets.UTF_8));
|
|
|
+ }
|
|
|
+ return encryptUserId(userId, publicKey);
|
|
|
+ }
|
|
|
+
|
|
|
+ private boolean isBlank(String value) {
|
|
|
+ return value == null || value.trim().isEmpty();
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 仿 AiGateway 的熔断判定。 */
|
|
|
+ private boolean isCircuitOpen() {
|
|
|
+ if (!circuitOpen) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ if (System.currentTimeMillis() - lastFailureTime.get() > resetTimeoutMs) {
|
|
|
+ circuitOpen = false;
|
|
|
+ consecutiveFailures.set(0);
|
|
|
+ log.info("AicdsGatewayService 熔断器已半开");
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 仿 AiGateway 的失败计数。 */
|
|
|
+ private void recordFailure() {
|
|
|
+ int failures = consecutiveFailures.incrementAndGet();
|
|
|
+ lastFailureTime.set(System.currentTimeMillis());
|
|
|
+ if (failures >= failureThreshold) {
|
|
|
+ circuitOpen = true;
|
|
|
+ log.warn("AicdsGatewayService 熔断器已打开 (连续{}次失败)", failures);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * AC11:错误归一。
|
|
|
+ * <ul>
|
|
|
+ * <li>401/403 → 鉴权失败;</li>
|
|
|
+ * <li>spu 空 → 未开通;</li>
|
|
|
+ * <li>子项为空 → 次数用完。</li>
|
|
|
+ * </ul>
|
|
|
+ */
|
|
|
+ public String normalizeError(int statusCode, String spu, Object subItems) {
|
|
|
+ if (statusCode == 401 || statusCode == 403) {
|
|
|
+ return "爱云医鉴权失败,请重新授权(HTTP " + statusCode + ")";
|
|
|
+ }
|
|
|
+ if (isBlank(spu)) {
|
|
|
+ return "爱云医检测未开通:当前用户无可用 SPU,请先开通检测服务";
|
|
|
+ }
|
|
|
+ if (isEmptySubItems(subItems)) {
|
|
|
+ return "爱云医检测次数用完:当前套餐无可用检测子项";
|
|
|
+ }
|
|
|
+ return "爱云医检测调用失败(HTTP " + statusCode + ")";
|
|
|
+ }
|
|
|
+
|
|
|
+ private boolean isEmptySubItems(Object subItems) {
|
|
|
+ if (subItems == null) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ if (subItems instanceof Collection) {
|
|
|
+ return ((Collection<?>) subItems).isEmpty();
|
|
|
+ }
|
|
|
+ if (subItems.getClass().isArray()) {
|
|
|
+ return Array.getLength(subItems) == 0;
|
|
|
+ }
|
|
|
+ if (subItems instanceof CharSequence) {
|
|
|
+ return ((CharSequence) subItems).length() == 0;
|
|
|
+ }
|
|
|
+ return false;
|
|
|
+ }
|
|
|
}
|