Browse Source

feat(S-cfc-471): 实现 ai.aiyunyi.gateway 宿主网关与配置类

扩展 AicdsGatewayService:RestTemplate 超时初始化(init)、熔断状态、统一 exchange 入口(鉴权头拼装/业务头)、normalizeError 错误归一;新增 AiYunyiProperties(@ConfigurationProperties prefix=aiyunyi) 含必填/超时字段与配置校验。AiyunyiGatewayContractTest 15/15 转绿。
zxyj-langgraph 2 hours ago
parent
commit
9f543ccfa7

+ 108 - 0
cfc-backend/src/main/java/com/etotem/cfc/config/AiYunyiProperties.java

@@ -0,0 +1,108 @@
+package com.etotem.cfc.config;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+/**
+ * 爱云医 AI 检测接入配置(能力键 {@code ai.aiyunyi.gateway},S-cfc-471)。
+ *
+ * <p>绑定 {@code application.yml} 中的 {@code aiyunyi.*},由
+ * {@code com.etotem.cfc.service.AicdsGatewayService} 统一加载使用。
+ * 私钥/公钥只存在于服务端配置,绝不下发前端(设计 §3.1)。</p>
+ */
+@Component
+@ConfigurationProperties(prefix = "aiyunyi")
+public class AiYunyiProperties {
+
+    /** appKey 契约占位默认值(设计示例值;生产须通过 aiyunyi.app-key 覆盖)。 */
+    public static final String DEFAULT_APP_KEY = "app-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
+    /** baseUrl 占位默认值(生产须通过 aiyunyi.base-url 覆盖)。 */
+    public static final String DEFAULT_BASE_URL = "http://localhost:9000";
+
+    private String appKey = DEFAULT_APP_KEY;
+    private String privateKey;
+    private String publicKey;
+    private String baseUrl = DEFAULT_BASE_URL;
+    private int timeoutMs = 5000;
+    private int readTimeoutMs = 15000;
+
+    public String getAppKey() {
+        return appKey;
+    }
+
+    public void setAppKey(String appKey) {
+        this.appKey = appKey;
+    }
+
+    public String getPrivateKey() {
+        return privateKey;
+    }
+
+    public void setPrivateKey(String privateKey) {
+        this.privateKey = privateKey;
+    }
+
+    public String getPublicKey() {
+        return publicKey;
+    }
+
+    public void setPublicKey(String publicKey) {
+        this.publicKey = publicKey;
+    }
+
+    public String getBaseUrl() {
+        return baseUrl;
+    }
+
+    public void setBaseUrl(String baseUrl) {
+        this.baseUrl = baseUrl;
+    }
+
+    public int getTimeoutMs() {
+        return timeoutMs;
+    }
+
+    public void setTimeoutMs(int timeoutMs) {
+        this.timeoutMs = timeoutMs;
+    }
+
+    public int getReadTimeoutMs() {
+        return readTimeoutMs;
+    }
+
+    public void setReadTimeoutMs(int readTimeoutMs) {
+        this.readTimeoutMs = readTimeoutMs;
+    }
+
+    /** 配置校验:必填项为空/空白或超时非正数时快速失败(禁止用空鉴权配置静默发请求)。 */
+    public void validateConfig() {
+        if (isBlank(appKey)) {
+            throw new IllegalStateException("aiyunyi.app-key 未配置");
+        }
+        if (isBlank(privateKey)) {
+            throw new IllegalStateException("aiyunyi.private-key 未配置");
+        }
+        if (isBlank(publicKey)) {
+            throw new IllegalStateException("aiyunyi.public-key 未配置");
+        }
+        if (isBlank(baseUrl)) {
+            throw new IllegalStateException("aiyunyi.base-url 未配置");
+        }
+        if (timeoutMs <= 0) {
+            throw new IllegalStateException("aiyunyi.timeout-ms 必须 > 0");
+        }
+        if (readTimeoutMs <= 0) {
+            throw new IllegalStateException("aiyunyi.read-timeout-ms 必须 > 0");
+        }
+    }
+
+    /** 配置是否完整(供调用方在发请求前判断;空白 appKey 必须返回 false)。 */
+    public boolean isConfigured() {
+        return !isBlank(appKey) && !isBlank(privateKey) && !isBlank(publicKey)
+                && !isBlank(baseUrl) && timeoutMs > 0 && readTimeoutMs > 0;
+    }
+
+    private boolean isBlank(String value) {
+        return value == null || value.trim().isEmpty();
+    }
+}

+ 220 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AicdsGatewayService.java

@@ -1,7 +1,19 @@
 package com.etotem.cfc.service;
 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.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.nio.charset.StandardCharsets;
 import java.security.KeyFactory;
 import java.security.KeyFactory;
 import java.security.PrivateKey;
 import java.security.PrivateKey;
@@ -10,9 +22,14 @@ import java.security.Signature;
 import java.security.spec.PKCS8EncodedKeySpec;
 import java.security.spec.PKCS8EncodedKeySpec;
 import java.security.spec.X509EncodedKeySpec;
 import java.security.spec.X509EncodedKeySpec;
 import java.util.Base64;
 import java.util.Base64;
+import java.util.Collection;
 import java.util.LinkedHashMap;
 import java.util.LinkedHashMap;
 import java.util.Map;
 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;
 import javax.crypto.Cipher;
 
 
 /**
 /**
@@ -145,4 +162,207 @@ public class AicdsGatewayService {
             throw new IllegalArgumentException("爱云医密钥 PEM 格式非法(Base64 解码失败)", e);
             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;
+    }
 }
 }