Initial project source

这个提交包含在:
apple
2026-11-20 15:32:57 +08:00
当前提交 fb47c07f7c
共修改 8405 个文件,包含 806907 行新增和 0 行删除
+26
查看文件
@@ -0,0 +1,26 @@
# 贝尔实验室 Spring 官方推荐镜像 JDK下载地址 https://bell-sw.com/pages/downloads/
FROM bellsoft/liberica-openjdk-rocky:21.0.12-cds
# FROM bellsoft/liberica-openjdk-rocky:25.0.4-cds
# FROM findepi/graalvm:java21-native
LABEL maintainer="AiXun Technology <343559364@qq.com>"
RUN mkdir -p /aixun-admin/gateway/logs \
/aixun-admin/gateway/temp \
/aixun-admin/skywalking/agent
WORKDIR /aixun-admin/gateway
ENV SERVER_PORT=8080 LANG=C.UTF-8 LC_ALL=C.UTF-8 JAVA_GC_OPTS="-XX:+UseZGC" JAVA_OPTS=""
EXPOSE ${SERVER_PORT}
ADD ./target/aixun-gateway.jar ./app.jar
SHELL ["/bin/bash", "-c"]
ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -Dserver.port=${SERVER_PORT} \
#-Dskywalking.agent.service_name=aixun-gateway \
#-javaagent:/aixun-admin/skywalking/agent/skywalking-agent.jar \
-XX:+HeapDumpOnOutOfMemoryError ${JAVA_GC_OPTS} ${JAVA_OPTS} \
-jar app.jar
+4
查看文件
@@ -0,0 +1,4 @@
此服务为 spring-cloud-gateway 的 Servlet MVC 版本
建议在JDK21启动虚拟线程的基础上使用 在JDK17下使用性能比原版差很多
+142
查看文件
@@ -0,0 +1,142 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-admin</artifactId>
<version>${revision}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>aixun-gateway</artifactId>
<description>
aixun-gateway 网关模块
</description>
<dependencies>
<!-- SpringCloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway-server-webmvc</artifactId>
</dependency>
<!-- SpringBoot Web容器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- Boot 4 下使用 jetty 替代 undertow -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-nacos</artifactId>
</dependency>
<!-- SpringBoot Actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
</dependency>
<!-- Sa-Token 权限认证 -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot4-starter</artifactId>
</dependency>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-satoken</artifactId>
</dependency>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-json</artifactId>
</dependency>
<!-- AiXun Common Redis-->
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 自定义负载均衡(多团队开发使用) -->
<!-- <dependency>-->
<!-- <groupId>cn.aixunkeji</groupId>-->
<!-- <artifactId>aixun-common-loadbalancer</artifactId>-->
<!-- </dependency>-->
<!-- ELK 日志收集 -->
<!-- <dependency>-->
<!-- <groupId>cn.aixunkeji</groupId>-->
<!-- <artifactId>aixun-common-logstash</artifactId>-->
<!-- </dependency>-->
<!-- skywalking 日志收集 -->
<!-- <dependency>-->
<!-- <groupId>cn.aixunkeji</groupId>-->
<!-- <artifactId>aixun-common-skylog</artifactId>-->
<!-- </dependency>-->
<!-- prometheus 监控 -->
<!-- <dependency>-->
<!-- <groupId>cn.aixunkeji</groupId>-->
<!-- <artifactId>aixun-common-prometheus</artifactId>-->
<!-- </dependency>-->
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,21 @@
package cn.aixunkeji.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
/**
* 网关启动程序
*
*/
@SpringBootApplication
public class AiXunGatewayApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(AiXunGatewayApplication.class);
application.setApplicationStartup(new BufferingApplicationStartup(2048));
application.run(args);
System.out.println("(♥◠‿◠)ノ゙ MVC网关启动成功 ლ(´ڡ`ლ)゙ ");
}
}
@@ -0,0 +1,70 @@
package cn.aixunkeji.gateway.config;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.LocaleResolver;
import java.util.List;
import java.util.Locale;
/**
* 网关配置
*
*/
@Configuration
public class GatewayConfig {
@Bean
public LocaleResolver localeResolver() {
return new LocaleResolver() {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String language = request.getHeader("content-language");
Locale locale = Locale.getDefault();
if (language == null || language.isBlank()) {
return locale;
}
String[] split = language.split("_");
if (split.length == 2) {
return new Locale(split[0], split[1]);
}
return Locale.forLanguageTag(language.replace('_', '-'));
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
// noop
}
};
}
@Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOriginPatterns(List.of("*"));
config.setAllowCredentials(true);
config.setAllowedHeaders(List.of(
"X-Requested-With", "Content-Language", "Content-Type",
"Authorization", "clientid", "credential", "X-XSRF-TOKEN",
"isToken", "token", "Admin-Token", "App-Token", "Encrypt-Key", "isEncrypt"
));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"));
config.setExposedHeaders(List.of("*"));
config.setMaxAge(18000L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean<CorsFilter> registration = new FilterRegistrationBean<>(new CorsFilter(source));
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registration;
}
}
@@ -0,0 +1,218 @@
package cn.aixunkeji.gateway.config;
import cn.aixunkeji.gateway.config.properties.GatewayHttpClientProperties;
import lombok.RequiredArgsConstructor;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder;
import org.springframework.boot.http.client.HttpClientSettings;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.HttpMethod;
import java.net.URI;
import java.time.Duration;
import java.util.regex.Pattern;
/**
* 网关 HttpClient5 配置
*
*/
@Configuration
@RequiredArgsConstructor
public class GatewayHttpClientConfig {
private static final String M2_STAGE_CALLBACK_PATH = "/internal/integration/v1/m2/stages";
private static final String DATA_SOURCE_PATH = "/api/integration/v1/data-sources/";
private static final String CONNECTION_TEST_SUFFIX = "/connection-tests";
private static final String UNIFIED_INGESTION_DRAFT_PATH = "/api/dataops/v1/unified-ingestions/draft";
private static final String UNIFIED_INGESTION_SUBMIT_PATH = "/api/dataops/v1/unified-ingestions/submit";
private static final String DATA_PROFILE_CREATE_PATH = "/api/governance/v1/data-profiles";
private static final String DATA_PROFILE_RETRY_PATH_PREFIX = "/api/governance/v1/data-profiles/";
private static final Pattern NUMERIC_ID = Pattern.compile("[0-9]+");
private static final Pattern METADATA_CATALOG_AI_DRAFT_PATH = Pattern.compile(
"/api/governance/v1/metadata-catalog/(?:TABLE|DATABASE_SCHEMA|DATABASE)/"
+ "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/"
+ "(?:business|management)/ai-draft");
private static final String STANDARD_ADOPTION_AI_MATCH_PATH =
"/api/governance/v1/standard-adoptions/ai-match";
private static final Pattern RUN_OPERATION_AI_DIAGNOSIS_PATH = Pattern.compile(
"/api/dataops/v1/run-operations/(?:SCHEDULING|BATCH_INGESTION|FILE_INGESTION|M2_GOLDEN)/"
+ "[1-9][0-9]*/ai-diagnosis");
private final GatewayHttpClientProperties properties;
/**
* Gateway MVC 使用 RestClient 转发请求,此处提供 HttpClient5 请求工厂以调整连接池参数
*/
@Bean
@RefreshScope
public ClientHttpRequestFactory gatewayClientHttpRequestFactory(HttpClientSettings settings) {
return ClientHttpRequestFactoryBuilder.httpComponents()
.withConnectionManagerCustomizer(connectionManager -> {
connectionManager.setMaxConnTotal(properties.getMaxConnTotal());
connectionManager.setMaxConnPerRoute(properties.getMaxConnPerRoute());
})
.withConnectionConfigCustomizer(connectionConfig -> {
if (properties.getConnectionTimeToLive() != null) {
connectionConfig.setTimeToLive(TimeValue.of(properties.getConnectionTimeToLive()));
}
if (properties.getValidateAfterInactivity() != null) {
connectionConfig.setValidateAfterInactivity(TimeValue.of(properties.getValidateAfterInactivity()));
}
})
.withDefaultRequestConfigCustomizer(requestConfig -> {
if (properties.getConnectionRequestTimeout() != null) {
requestConfig.setConnectionRequestTimeout(Timeout.of(properties.getConnectionRequestTimeout()));
}
if (properties.getResponseTimeout() != null) {
requestConfig.setResponseTimeout(Timeout.of(properties.getResponseTimeout()));
}
})
.withCustomizer(factory -> factory.setHttpContextFactory(
(method, uri) -> createRequestContext(method, uri, properties)))
.build(settings);
}
static HttpClientContext createRequestContext(String method, URI uri, GatewayHttpClientProperties properties) {
boolean dataProfileExecution = isDataProfileExecution(method, uri);
boolean metadataCatalogAiDraft = isMetadataCatalogAiDraft(method, uri)
&& isPositive(properties.getMetadataCatalogAiDraftResponseTimeout());
boolean standardAdoptionAiMatch = isStandardAdoptionAiMatch(method, uri)
&& isPositive(properties.getStandardAdoptionAiMatchResponseTimeout());
boolean runOperationAiDiagnosis = isRunOperationAiDiagnosis(method, uri)
&& isPositive(properties.getRunOperationAiDiagnosisResponseTimeout());
return createRequestContext(uri, properties, dataProfileExecution, metadataCatalogAiDraft,
standardAdoptionAiMatch, runOperationAiDiagnosis);
}
static HttpClientContext createRequestContext(HttpMethod method, URI uri, GatewayHttpClientProperties properties) {
return createRequestContext(method == null ? null : method.name(), uri, properties);
}
static HttpClientContext createRequestContext(URI uri, GatewayHttpClientProperties properties) {
return createRequestContext(uri, properties, false, false, false, false);
}
private static HttpClientContext createRequestContext(URI uri, GatewayHttpClientProperties properties,
boolean dataProfileExecution,
boolean metadataCatalogAiDraft,
boolean standardAdoptionAiMatch,
boolean runOperationAiDiagnosis) {
boolean m2StageCallback = isM2StageCallback(uri);
boolean dataSourceConnectionTest = isDataSourceConnectionTest(uri);
boolean unifiedIngestionDraft = isUnifiedIngestionDraft(uri);
boolean unifiedIngestionSubmit = isUnifiedIngestionSubmit(uri);
if (!dataProfileExecution && !m2StageCallback && !dataSourceConnectionTest && !unifiedIngestionDraft
&& !unifiedIngestionSubmit && !metadataCatalogAiDraft && !standardAdoptionAiMatch
&& !runOperationAiDiagnosis) return null;
RequestConfig.Builder requestConfig = RequestConfig.custom();
if (properties.getConnectionRequestTimeout() != null) {
requestConfig.setConnectionRequestTimeout(Timeout.of(properties.getConnectionRequestTimeout()));
}
if (m2StageCallback && properties.getM2CallbackResponseTimeout() != null) {
requestConfig.setResponseTimeout(Timeout.of(properties.getM2CallbackResponseTimeout()));
}
if (dataSourceConnectionTest && properties.getDataSourceConnectionTestResponseTimeout() != null) {
requestConfig.setResponseTimeout(Timeout.of(properties.getDataSourceConnectionTestResponseTimeout()));
}
if (unifiedIngestionDraft && properties.getUnifiedIngestionDraftResponseTimeout() != null) {
requestConfig.setResponseTimeout(Timeout.of(properties.getUnifiedIngestionDraftResponseTimeout()));
}
if (unifiedIngestionSubmit && properties.getUnifiedIngestionSubmitResponseTimeout() != null) {
requestConfig.setResponseTimeout(Timeout.of(properties.getUnifiedIngestionSubmitResponseTimeout()));
}
if (dataProfileExecution && properties.getDataProfileExecutionResponseTimeout() != null) {
requestConfig.setResponseTimeout(Timeout.of(properties.getDataProfileExecutionResponseTimeout()));
}
if (metadataCatalogAiDraft) {
requestConfig.setResponseTimeout(Timeout.of(properties.getMetadataCatalogAiDraftResponseTimeout()));
}
if (standardAdoptionAiMatch) {
requestConfig.setResponseTimeout(Timeout.of(properties.getStandardAdoptionAiMatchResponseTimeout()));
}
if (runOperationAiDiagnosis) {
requestConfig.setResponseTimeout(Timeout.of(properties.getRunOperationAiDiagnosisResponseTimeout()));
}
HttpClientContext context = HttpClientContext.create();
context.setRequestConfig(requestConfig.build());
return context;
}
static boolean isDataProfileExecution(String method, URI uri) {
if (!"POST".equalsIgnoreCase(method) || uri == null || uri.getPath() == null) {
return false;
}
String path = uri.getPath();
if (DATA_PROFILE_CREATE_PATH.equals(path)) {
return true;
}
if (!path.startsWith(DATA_PROFILE_RETRY_PATH_PREFIX) || !path.endsWith("/retry")) {
return false;
}
String requestId = path.substring(DATA_PROFILE_RETRY_PATH_PREFIX.length(), path.length() - "/retry".length());
return NUMERIC_ID.matcher(requestId).matches();
}
static boolean isMetadataCatalogAiDraft(String method, URI uri) {
return "POST".equalsIgnoreCase(method) && uri != null && uri.getPath() != null
&& METADATA_CATALOG_AI_DRAFT_PATH.matcher(uri.getPath()).matches();
}
static boolean isStandardAdoptionAiMatch(String method, URI uri) {
return "POST".equalsIgnoreCase(method) && uri != null
&& STANDARD_ADOPTION_AI_MATCH_PATH.equals(uri.getPath());
}
static boolean isRunOperationAiDiagnosis(String method, URI uri) {
return "POST".equalsIgnoreCase(method) && uri != null && uri.getPath() != null
&& RUN_OPERATION_AI_DIAGNOSIS_PATH.matcher(uri.getPath()).matches();
}
private static boolean isPositive(Duration value) {
return value != null && !value.isZero() && !value.isNegative();
}
static boolean isM2StageCallback(URI uri) {
if (uri == null || uri.getPath() == null) {
return false;
}
String path = uri.getPath();
return M2_STAGE_CALLBACK_PATH.equals(path) || path.startsWith(M2_STAGE_CALLBACK_PATH + "/");
}
static boolean isDataSourceConnectionTest(URI uri) {
if (uri == null || uri.getPath() == null) {
return false;
}
String path = uri.getPath();
if (path.equals(DATA_SOURCE_PATH + "connection-tests/transient")) {
return true;
}
if (!path.startsWith(DATA_SOURCE_PATH) || !path.endsWith(CONNECTION_TEST_SUFFIX)) {
return false;
}
if (path.length() <= DATA_SOURCE_PATH.length() + CONNECTION_TEST_SUFFIX.length()) {
return false;
}
String dataSourceId = path.substring(DATA_SOURCE_PATH.length(),
path.length() - CONNECTION_TEST_SUFFIX.length());
return !dataSourceId.isEmpty() &&
dataSourceId.chars().allMatch(character -> character >= '0' && character <= '9');
}
static boolean isUnifiedIngestionSubmit(URI uri) {
return uri != null && UNIFIED_INGESTION_SUBMIT_PATH.equals(uri.getPath());
}
static boolean isUnifiedIngestionDraft(URI uri) {
return uri != null && UNIFIED_INGESTION_DRAFT_PATH.equals(uri.getPath());
}
}
@@ -0,0 +1,28 @@
package cn.aixunkeji.gateway.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* api解密属性配置类
*
*/
@Data
@Component
@RefreshScope
@ConfigurationProperties(prefix = "api-decrypt")
public class ApiDecryptProperties {
/**
* 加密开关
*/
private Boolean enabled;
/**
* 头部标识
*/
private String headerFlag;
}
@@ -0,0 +1,23 @@
package cn.aixunkeji.gateway.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
/**
* 自定义gateway参数配置
*
*/
@Data
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "spring.cloud.gateway")
public class CustomGatewayProperties {
/**
* 请求日志
*/
private Boolean requestLog;
}
@@ -0,0 +1,90 @@
package cn.aixunkeji.gateway.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import java.time.Duration;
/**
* 网关 HttpClient5 配置
*
*/
@Data
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "spring.cloud.gateway.httpclient")
public class GatewayHttpClientProperties {
/**
* 连接池最大连接数
*/
private Integer maxConnTotal = 1000;
/**
* 单个路由最大连接数
*/
private Integer maxConnPerRoute = 500;
/**
* 从连接池获取连接的等待超时时间
*/
private Duration connectionRequestTimeout = Duration.ofSeconds(3);
/**
* 普通路由等待下游响应数据的超时时间
*/
private Duration responseTimeout = Duration.ofSeconds(10);
/**
* M2内部阶段回调等待下游响应数据的超时时间
*/
private Duration m2CallbackResponseTimeout = Duration.ofSeconds(450);
/**
* 数据源连接测试等待 Integration 返回归一化外部结果的超时时间
*/
private Duration dataSourceConnectionTestResponseTimeout = Duration.ofSeconds(75);
/**
* 统一数据采集逐表读取源结构并生成字段映射草稿的等待时间
*/
private Duration unifiedIngestionDraftResponseTimeout = Duration.ofSeconds(120);
/**
* 统一数据采集逐表提交等待下游建表、READY和外部提交的超时时间
*/
private Duration unifiedIngestionSubmitResponseTimeout = Duration.ofSeconds(180);
/**
* 数据画像创建及数字ID重试等待Governance同步执行完成的超时时间
*/
private Duration dataProfileExecutionResponseTimeout = Duration.ofSeconds(120);
/**
* 元数据目录业务/管理AI草稿等待下游完成的超时时间
*/
private Duration metadataCatalogAiDraftResponseTimeout = Duration.ofSeconds(75);
/**
* 落标新增表单AI标准推荐等待下游完成的超时时间
*/
private Duration standardAdoptionAiMatchResponseTimeout = Duration.ofSeconds(75);
/**
* 失败运行详情AI诊断等待DataOps与受管Provider完成的超时时间
*/
private Duration runOperationAiDiagnosisResponseTimeout = Duration.ofSeconds(75);
/**
* 连接最大存活时间
*/
private Duration connectionTimeToLive;
/**
* 空闲连接可用性校验间隔
*/
private Duration validateAfterInactivity = Duration.ofSeconds(30);
}
@@ -0,0 +1,28 @@
package cn.aixunkeji.gateway.config.properties;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
/**
* 放行白名单配置
*
*/
@Data
@NoArgsConstructor
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "security.ignore")
public class IgnoreWhiteProperties {
/**
* 放行白名单配置,网关不校验此处的白名单
*/
private List<String> whites = new ArrayList<>();
}
@@ -0,0 +1,153 @@
package cn.aixunkeji.gateway.filter;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.filter.SaTokenContextFilterForJakartaServlet;
import cn.dev33.satoken.httpauth.basic.SaHttpBasicUtil;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.dev33.satoken.util.SaTokenConsts;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import cn.aixunkeji.common.core.constant.HttpStatus;
import cn.aixunkeji.common.core.utils.NetUtils;
import cn.aixunkeji.common.core.utils.ServletUtils;
import cn.aixunkeji.common.core.utils.SpringUtils;
import cn.aixunkeji.common.core.utils.StringUtils;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.aixunkeji.gateway.config.properties.IgnoreWhiteProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import java.util.EnumSet;
import java.util.List;
/**
* [Sa-Token 权限认证] 过滤器配置
*
*/
@Configuration
public class AuthFilter {
private static final String CLIENT_RULE_SEPARATOR_REGEX = "[,;\\r\\n]+";
private final IgnoreWhiteProperties ignoreWhite;
public AuthFilter(IgnoreWhiteProperties ignoreWhite) {
this.ignoreWhite = ignoreWhite;
}
/**
* 重新注册 Sa-Token 上下文过滤器,使其覆盖网关 SSE/WebSocket 异步分发。
*
* @param filter Sa-Token 官方上下文过滤器
* @return 过滤器注册配置
*/
@Bean
public FilterRegistrationBean<SaTokenContextFilterForJakartaServlet> saTokenContextFilterRegistration(
SaTokenContextFilterForJakartaServlet filter) {
FilterRegistrationBean<SaTokenContextFilterForJakartaServlet> registration = new FilterRegistrationBean<>();
registration.setFilter(filter);
registration.setName("saTokenContextFilterForServlet");
registration.addUrlPatterns("/*");
registration.setDispatcherTypes(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC, DispatcherType.ERROR));
registration.setAsyncSupported(true);
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registration;
}
/**
* 注册 Sa-Token 全局过滤器
*/
@Bean
public SaServletFilter authSaServletFilter() {
return new SaServletFilter()
.addInclude("/**")
.addExclude("/favicon.ico", "/actuator", "/actuator/**", "/error")
.setAuth(obj -> SaRouter.match("/**")
.notMatch(ignoreWhite.getWhites())
.check(() -> {
HttpServletRequest request = ServletUtils.getRequest();
StpUtil.checkLogin();
String headerCid = request.getHeader(LoginHelper.CLIENT_KEY);
String paramCid = ServletUtils.getParameter(LoginHelper.CLIENT_KEY);
Object extra = StpUtil.getExtra(LoginHelper.CLIENT_KEY);
String clientId = extra == null ? null : extra.toString();
if (!StringUtils.equalsAny(clientId, headerCid, paramCid)) {
throw NotLoginException.newInstance(StpUtil.getLoginType(),
"-100", "客户端ID与Token不匹配",
null);
}
validateClientAccessRules(request);
}))
.setError(e -> {
HttpServletResponse response = ServletUtils.getResponse();
response.setContentType(SaTokenConsts.CONTENT_TYPE_APPLICATION_JSON);
if (e instanceof NotLoginException) {
return SaResult.error("未登录或登录已失效").setCode(HttpStatus.UNAUTHORIZED);
}
return SaResult.error("认证失败,无法访问系统资源").setCode(HttpStatus.UNAUTHORIZED);
});
}
/**
* 为 actuator 健康检查接口配置 Basic Auth 鉴权过滤器。
*
* @return Sa-Token Servlet 过滤器
*/
@Bean
public SaServletFilter getSaServletFilter() {
String username = SpringUtils.getProperty("spring.cloud.nacos.discovery.metadata.username");
String password = SpringUtils.getProperty("spring.cloud.nacos.discovery.metadata.userpassword");
return new SaServletFilter()
.addInclude("/actuator", "/actuator/**")
.setAuth(obj -> {
SaHttpBasicUtil.check(username + StringUtils.COLON + password);
})
.setError(e -> {
HttpServletResponse response = ServletUtils.getResponse();
response.setContentType(SaTokenConsts.CONTENT_TYPE_APPLICATION_JSON);
return SaResult.error(e.getMessage()).setCode(HttpStatus.UNAUTHORIZED);
});
}
/**
* 按客户端配置校验接口访问路径与来源IP。
*/
private void validateClientAccessRules(HttpServletRequest request) {
String requestPath = StringUtils.blankToDefault(request.getServletPath(), request.getRequestURI());
String accessPath = getTokenExtra(LoginHelper.CLIENT_ACCESS_PATH_KEY);
if (StringUtils.isNotBlank(accessPath)) {
List<String> accessPathList = StringUtils.str2List(accessPath, CLIENT_RULE_SEPARATOR_REGEX, true, true);
if (!StringUtils.matches(requestPath, accessPathList)) {
throw new NotPermissionException("当前客户端未授权访问该接口路径");
}
}
String ipWhitelist = getTokenExtra(LoginHelper.CLIENT_IP_WHITELIST_KEY);
if (StringUtils.isNotBlank(ipWhitelist)) {
String clientIp = ServletUtils.getClientIP(request);
List<String> ipWhitelistList = StringUtils.str2List(ipWhitelist, CLIENT_RULE_SEPARATOR_REGEX, true, true);
boolean matched = ipWhitelistList.stream().anyMatch(rule -> NetUtils.isMatchIpRule(rule, clientIp));
if (!matched) {
throw new NotPermissionException("当前客户端IP不在白名单内");
}
}
}
/**
* 读取token扩展信息,兼容空值场景。
*/
private String getTokenExtra(String key) {
Object extra = StpUtil.getExtra(key);
return extra == null ? null : extra.toString();
}
}
@@ -0,0 +1,48 @@
package cn.aixunkeji.gateway.filter;
import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.same.SaSameUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import cn.aixunkeji.gateway.filter.support.MutableHttpServletRequest;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/**
* 转发请求头过滤器:
* 1. 转发内部 same-token
*
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 15)
public class ForwardAuthFilter extends OncePerRequestFilter {
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return request.getRequestURI().startsWith("/actuator");
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
MutableHttpServletRequest newRequest = null;
if (SaManager.getConfig().getCheckSameToken()) {
newRequest = getOrCreateMutableRequest(request, newRequest);
newRequest.putHeader(SaSameUtil.SAME_TOKEN, SaSameUtil.getToken());
}
filterChain.doFilter(newRequest == null ? request : newRequest, response);
}
private MutableHttpServletRequest getOrCreateMutableRequest(HttpServletRequest request,
MutableHttpServletRequest currentRequest) {
return currentRequest != null ? currentRequest : new MutableHttpServletRequest(request);
}
}
@@ -0,0 +1,51 @@
package cn.aixunkeji.gateway.filter;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.cloud.gateway.server.mvc.filter.HttpHeadersFilter.RequestHttpHeadersFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.function.ServerRequest;
import java.util.List;
import java.util.Map;
/**
* Gateway MVC 下游请求头过滤器,补充服务访问前缀。
*
*/
@Component
public class ForwardHeadersFilter implements RequestHttpHeadersFilter, Ordered {
private static final String X_FORWARDED_PREFIX = "X-Forwarded-Prefix";
@Override
public int getOrder() {
return 1;
}
@Override
public HttpHeaders apply(HttpHeaders input, ServerRequest request) {
String forwardedPrefix = resolveForwardedPrefix(request.servletRequest());
if (forwardedPrefix == null) {
return input;
}
HttpHeaders headers = new HttpHeaders();
for (Map.Entry<String, List<String>> entry : input.headerSet()) {
headers.addAll(entry.getKey(), entry.getValue());
}
headers.set(X_FORWARDED_PREFIX, forwardedPrefix);
return headers;
}
private String resolveForwardedPrefix(HttpServletRequest request) {
String[] pathSegments = StringUtils.tokenizeToStringArray(request.getRequestURI(), "/");
if (pathSegments.length == 0) {
return null;
}
return "/" + pathSegments[0];
}
}
@@ -0,0 +1,120 @@
package cn.aixunkeji.gateway.filter;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import cn.aixunkeji.common.core.constant.SystemConstants;
import cn.aixunkeji.common.core.utils.StringUtils;
import cn.aixunkeji.common.json.utils.JsonUtils;
import cn.aixunkeji.gateway.config.properties.ApiDecryptProperties;
import cn.aixunkeji.gateway.config.properties.CustomGatewayProperties;
import cn.aixunkeji.gateway.filter.support.CachedBodyHttpServletRequest;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.UriComponentsBuilder;
import tools.jackson.databind.JsonNode;
import java.io.IOException;
/**
* 全局日志过滤器
* <p>
* 用于打印请求执行参数与响应时间等等
*
*/
@Slf4j
@Component
@Order(Ordered.LOWEST_PRECEDENCE - 10)
public class GlobalLogFilter extends OncePerRequestFilter {
private final CustomGatewayProperties customGatewayProperties;
private final ApiDecryptProperties apiDecryptProperties;
public GlobalLogFilter(CustomGatewayProperties customGatewayProperties, ApiDecryptProperties apiDecryptProperties) {
this.customGatewayProperties = customGatewayProperties;
this.apiDecryptProperties = apiDecryptProperties;
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return !Boolean.TRUE.equals(customGatewayProperties.getRequestLog());
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HttpServletRequest requestToUse = request;
if (isJsonRequest(request) && !(request instanceof CachedBodyHttpServletRequest)) {
requestToUse = new CachedBodyHttpServletRequest(request);
}
String url = requestToUse.getMethod() + " " + requestToUse.getRequestURI();
logRequest(requestToUse, url);
long startTime = System.currentTimeMillis();
try {
filterChain.doFilter(requestToUse, response);
} finally {
log.info("[PLUS]结束请求 => URL[{}],耗时:[{}]毫秒", url, System.currentTimeMillis() - startTime);
}
}
private void logRequest(HttpServletRequest request, String url) {
if (isJsonRequest(request)) {
if (Boolean.TRUE.equals(apiDecryptProperties.getEnabled())
&& ObjectUtil.isNotNull(request.getHeader(apiDecryptProperties.getHeaderFlag()))) {
log.info("[PLUS]开始请求 => URL[{}],参数类型[encrypt]", url);
return;
}
String jsonParam = resolveBody(request);
if (StringUtils.isNotBlank(jsonParam)) {
jsonParam = removeSensitiveFields(jsonParam);
}
log.info("[PLUS]开始请求 => URL[{}],参数类型[json],参数:[{}]", url, jsonParam);
return;
}
MultiValueMap<String, String> parameterMap = UriComponentsBuilder.newInstance()
.query(request.getQueryString())
.build()
.getQueryParams();
if (MapUtil.isNotEmpty(parameterMap)) {
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>(parameterMap);
MapUtil.removeAny(map, SystemConstants.EXCLUDE_PROPERTIES);
log.info("[PLUS]开始请求 => URL[{}],参数类型[param],参数:[{}]", url, JsonUtils.toJsonString(map));
} else {
log.info("[PLUS]开始请求 => URL[{}],无参数", url);
}
}
private boolean isJsonRequest(HttpServletRequest request) {
return StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE);
}
private String resolveBody(HttpServletRequest request) {
if (request instanceof CachedBodyHttpServletRequest cachedRequest) {
return cachedRequest.getCachedBodyAsString();
}
return null;
}
private String removeSensitiveFields(String jsonParam) {
try {
JsonNode rootNode = JsonUtils.getJsonMapper().readTree(jsonParam);
JsonUtils.removeFields(rootNode, SystemConstants.EXCLUDE_PROPERTIES);
return rootNode.toString();
} catch (Exception ex) {
return jsonParam;
}
}
}
@@ -0,0 +1,69 @@
package cn.aixunkeji.gateway.filter.support;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.springframework.util.StreamUtils;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* 可重复读取请求体的包装类
*
*/
public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {
private final byte[] cachedBody;
public CachedBodyHttpServletRequest(HttpServletRequest request) throws IOException {
super(request);
this.cachedBody = StreamUtils.copyToByteArray(request.getInputStream());
}
@Override
public ServletInputStream getInputStream() {
ByteArrayInputStream inputStream = new ByteArrayInputStream(cachedBody);
return new ServletInputStream() {
@Override
public int read() {
return inputStream.read();
}
@Override
public boolean isFinished() {
return inputStream.available() == 0;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener listener) {
// noop
}
};
}
@Override
public BufferedReader getReader() {
Charset charset = getCharacterEncoding() == null
? StandardCharsets.UTF_8
: Charset.forName(getCharacterEncoding());
return new BufferedReader(new InputStreamReader(getInputStream(), charset));
}
public String getCachedBodyAsString() {
Charset charset = getCharacterEncoding() == null
? StandardCharsets.UTF_8
: Charset.forName(getCharacterEncoding());
return new String(cachedBody, charset);
}
}
@@ -0,0 +1,49 @@
package cn.aixunkeji.gateway.filter.support;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import java.util.*;
/**
* 可追加请求头的包装类
*
*/
public class MutableHttpServletRequest extends HttpServletRequestWrapper {
private final Map<String, String> customHeaders = new LinkedHashMap<>();
public MutableHttpServletRequest(HttpServletRequest request) {
super(request);
}
public void putHeader(String name, String value) {
customHeaders.put(name, value);
}
@Override
public String getHeader(String name) {
String value = customHeaders.get(name);
return value != null ? value : super.getHeader(name);
}
@Override
public Enumeration<String> getHeaders(String name) {
String value = customHeaders.get(name);
if (value != null) {
return Collections.enumeration(Collections.singletonList(value));
}
return super.getHeaders(name);
}
@Override
public Enumeration<String> getHeaderNames() {
Set<String> names = new LinkedHashSet<>();
Enumeration<String> headerNames = super.getHeaderNames();
while (headerNames.hasMoreElements()) {
names.add(headerNames.nextElement());
}
names.addAll(customHeaders.keySet());
return new Vector<>(names).elements();
}
}
@@ -0,0 +1,75 @@
package cn.aixunkeji.gateway.handler;
import cn.dev33.satoken.exception.NotLoginException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import cn.aixunkeji.common.core.constant.HttpStatus;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.common.json.utils.JsonUtils;
import org.springframework.http.MediaType;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* 网关统一异常处理
*
*/
@Slf4j
@RestControllerAdvice
public class GatewayExceptionHandler {
@ExceptionHandler(NotLoginException.class)
public void handleNotLogin(HttpServletRequest request, HttpServletResponse response, NotLoginException ex) throws IOException {
log.warn("[网关认证失败]请求路径:{},异常信息:{}", request.getRequestURI(), ex.getMessage());
writeJson(response, HttpStatus.UNAUTHORIZED, ex.getMessage());
}
@ExceptionHandler(Throwable.class)
public void handle(HttpServletRequest request, HttpServletResponse response, Throwable ex) throws IOException {
GatewayError error = mapError(ex);
int code = error.code();
String msg = error.message();
String exceptionMessage = ex.getMessage();
if (code == HttpStatus.NOT_FOUND || code == HttpStatus.BAD_METHOD) {
log.warn("[网关请求拒绝]请求路径:{},状态码:{},异常信息:{}", request.getRequestURI(), code, exceptionMessage);
} else {
log.error("[网关异常处理]请求路径:{},异常信息:{}", request.getRequestURI(), exceptionMessage, ex);
}
writeJson(response, code, msg);
}
static GatewayError mapError(Throwable ex) {
String exceptionMessage = ex.getMessage();
if (ex instanceof NoHandlerFoundException) {
return new GatewayError(HttpStatus.NOT_FOUND, "请求地址不存在");
}
if (ex instanceof HttpRequestMethodNotSupportedException) {
return new GatewayError(HttpStatus.BAD_METHOD, "请求方式不支持");
}
if ("NotFoundException".equals(ex.getClass().getSimpleName())
|| (exceptionMessage != null && exceptionMessage.contains("Unable to find instance"))) {
return new GatewayError(HttpStatus.NOT_FOUND, "服务未找到");
}
if (ex instanceof ResponseStatusException responseStatusException) {
return new GatewayError(responseStatusException.getStatusCode().value(), responseStatusException.getMessage());
}
return new GatewayError(HttpStatus.ERROR, "内部服务器错误");
}
private void writeJson(HttpServletResponse response, int code, String msg) throws IOException {
response.setStatus(code);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write(JsonUtils.toJsonString(R.fail(code, msg)));
}
record GatewayError(int code, String message) {
}
}
@@ -0,0 +1,35 @@
# Tomcat
server:
port: 8080
servlet:
context-path: /
# Spring
spring:
application:
# 应用名称
name: aixun-gateway
profiles:
# 环境配置
active: @profiles.active@
--- # nacos 配置
spring:
cloud:
nacos:
# nacos 服务地址
server-addr: @nacos.server@
username: @nacos.username@
password: @nacos.password@
discovery:
# 注册组
group: DEFAULT_GROUP
namespace: public
config:
# 配置组
group: DEFAULT_GROUP
namespace: public
config:
import:
- optional:nacos:application-common.yml
- optional:nacos:${spring.application.name}.yml
@@ -0,0 +1,10 @@
Spring Boot Version: ${spring-boot.version}
Spring Application Name: ${spring.application.name}
_ _
(_) | |
_ __ _ _ ___ _ _ _ ______ __ _ __ _ | |_ ___ __ __ __ _ _ _
| '__|| | | | / _ \ | | | || ||______| / _` | / _` || __| / _ \\ \ /\ / / / _` || | | |
| | | |_| || (_) || |_| || | | (_| || (_| || |_ | __/ \ V V / | (_| || |_| |
|_| \__,_| \___/ \__, ||_| \__, | \__,_| \__| \___| \_/\_/ \__,_| \__, |
__/ | __/ | __/ |
|___/ |___/ |___/
@@ -0,0 +1,114 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 日志存放路径 -->
<property name="log.path" value="logs/${project.artifactId}"/>
<!-- 日志输出格式 -->
<property name="console.log.pattern"
value="%cyan(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}%n) - %msg%n"/>
<property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"/>
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${console.log.pattern}</pattern>
<charset>utf-8</charset>
</encoder>
</appender>
<!-- 控制台输出 -->
<appender name="file_console" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/console.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/console.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大 1天 -->
<maxHistory>1</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
<charset>utf-8</charset>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
</filter>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- info异步输出 -->
<appender name="async_info" class="ch.qos.logback.classic.AsyncAppender">
<!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
<discardingThreshold>0</discardingThreshold>
<!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
<queueSize>512</queueSize>
<!-- 添加附加的appender,最多只能添加一个 -->
<appender-ref ref="file_info"/>
</appender>
<!-- error异步输出 -->
<appender name="async_error" class="ch.qos.logback.classic.AsyncAppender">
<!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
<discardingThreshold>0</discardingThreshold>
<!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
<queueSize>512</queueSize>
<!-- 添加附加的appender,最多只能添加一个 -->
<appender-ref ref="file_error"/>
</appender>
<include resource="logback-logstash.xml" />
<!-- 开启 skywalking 日志收集 -->
<include resource="logback-skylog.xml" />
<!--系统操作日志-->
<root level="info">
<appender-ref ref="console"/>
<appender-ref ref="async_info"/>
<appender-ref ref="async_error"/>
<appender-ref ref="file_console"/>
</root>
</configuration>
@@ -0,0 +1,320 @@
package cn.aixunkeji.gateway.config;
import cn.aixunkeji.gateway.config.properties.GatewayHttpClientProperties;
import com.sun.net.httpserver.HttpServer;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.junit.jupiter.api.Test;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class GatewayHttpClientConfigTest {
private final GatewayHttpClientProperties properties = new GatewayHttpClientProperties();
@Test
void defaultsKeepNormalAndM2TimeoutsSeparate() {
assertThat(properties.getConnectionRequestTimeout()).isEqualTo(Duration.ofSeconds(3));
assertThat(properties.getResponseTimeout()).isEqualTo(Duration.ofSeconds(10));
assertThat(properties.getM2CallbackResponseTimeout()).isEqualTo(Duration.ofSeconds(450));
assertThat(properties.getDataSourceConnectionTestResponseTimeout()).isEqualTo(Duration.ofSeconds(75));
assertThat(properties.getUnifiedIngestionDraftResponseTimeout()).isEqualTo(Duration.ofSeconds(120));
assertThat(properties.getUnifiedIngestionSubmitResponseTimeout()).isEqualTo(Duration.ofSeconds(180));
assertThat(properties.getDataProfileExecutionResponseTimeout()).isEqualTo(Duration.ofSeconds(120));
assertThat(properties.getMetadataCatalogAiDraftResponseTimeout()).isEqualTo(Duration.ofSeconds(75));
assertThat(properties.getStandardAdoptionAiMatchResponseTimeout()).isEqualTo(Duration.ofSeconds(75));
assertThat(properties.getRunOperationAiDiagnosisResponseTimeout()).isEqualTo(Duration.ofSeconds(75));
}
@Test
void createsBoundedLongTimeoutOnlyForExactRunOperationAiDiagnosisPost() {
for (String source : List.of("SCHEDULING", "BATCH_INGESTION", "FILE_INGESTION", "M2_GOLDEN")) {
URI uri = URI.create("http://aixun-dataops/api/dataops/v1/run-operations/" + source
+ "/19/ai-diagnosis?trace=1");
HttpClientContext context = GatewayHttpClientConfig.createRequestContext("POST", uri, properties);
assertThat(context.getRequestConfig().getResponseTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(75));
}
URI valid = URI.create(
"http://aixun-dataops/api/dataops/v1/run-operations/SCHEDULING/19/ai-diagnosis");
for (String method : List.of("GET", "PUT", "DELETE")) {
assertThat(GatewayHttpClientConfig.createRequestContext(method, valid, properties)).isNull();
}
for (URI uri : List.of(
URI.create("http://aixun-dataops/api/dataops/v1/run-operations/SCHEDULING/0/ai-diagnosis"),
URI.create("http://aixun-dataops/api/dataops/v1/run-operations/scheduling/19/ai-diagnosis"),
URI.create("http://aixun-dataops/api/dataops/v1/run-operations/UNKNOWN/19/ai-diagnosis"),
URI.create("http://aixun-dataops/api/dataops/v1/run-operations/SCHEDULING/19/ai-diagnosis/"),
URI.create("http://aixun-dataops/api/dataops/v1/run-operations/SCHEDULING/19/ai-diagnosis-extra")
)) assertThat(GatewayHttpClientConfig.createRequestContext("POST", uri, properties)).isNull();
}
@Test
void rejectsInvalidRunOperationAiDiagnosisTimeouts() {
URI uri = URI.create(
"http://aixun-dataops/api/dataops/v1/run-operations/SCHEDULING/19/ai-diagnosis");
for (Duration invalid : java.util.Arrays.asList(null, Duration.ZERO, Duration.ofSeconds(-1))) {
properties.setRunOperationAiDiagnosisResponseTimeout(invalid);
assertThat(GatewayHttpClientConfig.createRequestContext("POST", uri, properties)).isNull();
}
}
@Test
void createsBoundedLongTimeoutOnlyForExactStandardAdoptionAiMatchPost() {
URI valid = URI.create("http://aixun-governance/api/governance/v1/standard-adoptions/ai-match?trace=1");
HttpClientContext context = GatewayHttpClientConfig.createRequestContext("POST", valid, properties);
assertThat(context.getRequestConfig().getResponseTimeout().toDuration()).isEqualTo(Duration.ofSeconds(75));
for (String method : List.of("GET", "PUT", "DELETE")) {
assertThat(GatewayHttpClientConfig.createRequestContext(method, valid, properties)).isNull();
}
for (URI uri : List.of(
URI.create("http://aixun-governance/api/governance/v1/standard-adoptions/ai-match/"),
URI.create("http://aixun-governance/api/governance/v1/standard-adoptions/ai-match-extra"),
URI.create("http://aixun-governance/api/governance/v1/standard-adoptions/1/ai-match")
)) assertThat(GatewayHttpClientConfig.createRequestContext("POST", uri, properties)).isNull();
}
@Test
void rejectsInvalidStandardAdoptionAiMatchTimeouts() {
URI uri = URI.create("http://aixun-governance/api/governance/v1/standard-adoptions/ai-match");
for (Duration invalid : java.util.Arrays.asList(null, Duration.ZERO, Duration.ofSeconds(-1))) {
properties.setStandardAdoptionAiMatchResponseTimeout(invalid);
assertThat(GatewayHttpClientConfig.createRequestContext("POST", uri, properties)).isNull();
}
}
@Test
void standardAdoptionAiMatchContextReceivesARealResponseAfterNormalTenSecondBudget() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
String path = "/api/governance/v1/standard-adoptions/ai-match";
server.createContext(path, exchange -> {
try {
Thread.sleep(10_250);
byte[] body = "ok".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
exchange.sendResponseHeaders(503, -1);
} finally { exchange.close(); }
});
server.start();
try (CloseableHttpClient client = HttpClients.createDefault()) {
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + path);
HttpClientContext context = GatewayHttpClientConfig.createRequestContext("POST", uri, properties);
int status = client.execute(new HttpPost(uri), context, response -> response.getCode());
assertThat(status).isEqualTo(200);
} finally { server.stop(0); }
}
@Test
void createsBoundedLongTimeoutOnlyForExactMetadataCatalogAiDraftPosts() {
for (URI uri : List.of(
URI.create("http://aixun-governance/api/governance/v1/metadata-catalog/TABLE/123e4567-e89b-12d3-a456-426614174000/business/ai-draft"),
URI.create("http://aixun-governance/api/governance/v1/metadata-catalog/DATABASE_SCHEMA/123e4567-e89b-12d3-a456-426614174000/management/ai-draft?trace=1"),
URI.create("http://aixun-governance/api/governance/v1/metadata-catalog/DATABASE/ABCDEF12-3456-7890-ABCD-EF1234567890/business/ai-draft")
)) {
HttpClientContext context = GatewayHttpClientConfig.createRequestContext("POST", uri, properties);
assertThat(context.getRequestConfig().getConnectionRequestTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(3));
assertThat(context.getRequestConfig().getResponseTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(75));
}
}
@Test
void leavesMetadataCatalogAiDraftNearMatchesOnDefaultTimeout() {
URI valid = URI.create("http://aixun-governance/api/governance/v1/metadata-catalog/TABLE/123e4567-e89b-12d3-a456-426614174000/business/ai-draft");
for (String method : List.of("GET", "PUT", "DELETE")) {
assertThat(GatewayHttpClientConfig.createRequestContext(method, valid, properties)).isNull();
}
for (URI uri : List.of(
URI.create("http://aixun-governance/api/governance/v1/metadata-catalog/TABLE/not-a-uuid/business/ai-draft"),
URI.create("http://aixun-governance/api/governance/v1/metadata-catalog/PIPELINE/123e4567-e89b-12d3-a456-426614174000/business/ai-draft"),
URI.create("http://aixun-governance/api/governance/v1/metadata-catalog/TABLE/123e4567-e89b-12d3-a456-426614174000/security/ai-draft"),
URI.create("http://aixun-governance/api/governance/v1/metadata-catalog/TABLE/123e4567-e89b-12d3-a456-426614174000/business/ai-draft/"),
URI.create("http://aixun-governance/api/governance/v1/metadata-catalog/TABLE/123e4567-e89b-12d3-a456-426614174000/business/ai-draft-extra"),
URI.create("http://aixun-governance/api/governance/v1/metadata-catalog/TABLE/123e4567-e89b-12d3-a456-426614174000/business")
)) {
assertThat(GatewayHttpClientConfig.createRequestContext("POST", uri, properties)).isNull();
}
assertThat(GatewayHttpClientConfig.createRequestContext(valid, properties)).isNull();
}
@Test
void rejectsInvalidMetadataCatalogAiDraftTimeoutsWithoutCreatingAnUnboundedOverride() {
URI uri = URI.create("http://aixun-governance/api/governance/v1/metadata-catalog/TABLE/123e4567-e89b-12d3-a456-426614174000/management/ai-draft");
for (Duration invalid : java.util.Arrays.asList(null, Duration.ZERO, Duration.ofSeconds(-1))) {
properties.setMetadataCatalogAiDraftResponseTimeout(invalid);
assertThat(GatewayHttpClientConfig.createRequestContext("POST", uri, properties)).isNull();
}
}
@Test
void metadataCatalogAiDraftContextReceivesARealResponseAfterTheNormalTenSecondBudget() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
String path = "/api/governance/v1/metadata-catalog/TABLE/123e4567-e89b-12d3-a456-426614174000/management/ai-draft";
server.createContext(path, exchange -> {
try {
Thread.sleep(10_250);
byte[] body = "ok".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
exchange.sendResponseHeaders(503, -1);
} finally {
exchange.close();
}
});
server.start();
try (CloseableHttpClient client = HttpClients.createDefault()) {
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + path);
HttpClientContext context = GatewayHttpClientConfig.createRequestContext("POST", uri, properties);
int status = client.execute(new HttpPost(uri), context, response -> response.getCode());
assertThat(status).isEqualTo(200);
} finally {
server.stop(0);
}
}
@Test
void createsBoundedLongTimeoutOnlyForExactDataProfilePostPaths() {
for (URI uri : List.of(
URI.create("http://aixun-governance/api/governance/v1/data-profiles"),
URI.create("http://aixun-governance/api/governance/v1/data-profiles?trace=1"),
URI.create("http://aixun-governance/api/governance/v1/data-profiles/2104862540773793794/retry")
)) {
HttpClientContext context = GatewayHttpClientConfig.createRequestContext("POST", uri, properties);
assertThat(context.getRequestConfig().getConnectionRequestTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(3));
assertThat(context.getRequestConfig().getResponseTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(120));
}
}
@Test
void leavesDataProfileGetFakeIdAndNearMatchesOnDefaultTimeout() {
for (String method : List.of("GET", "PUT")) {
for (URI uri : List.of(
URI.create("http://aixun-governance/api/governance/v1/data-profiles"),
URI.create("http://aixun-governance/api/governance/v1/data-profiles/1/retry")
)) {
assertThat(GatewayHttpClientConfig.createRequestContext(method, uri, properties)).isNull();
}
}
for (URI uri : List.of(
URI.create("http://aixun-governance/api/governance/v1/data-profiles/not-a-number/retry"),
URI.create("http://aixun-governance/api/governance/v1/data-profiles/1/retry/extra"),
URI.create("http://aixun-governance/api/governance/v1/data-profilesx"),
URI.create("http://aixun-governance/api/governance/v1/data-profiles/1/retryx")
)) {
assertThat(GatewayHttpClientConfig.createRequestContext("POST", uri, properties)).isNull();
}
}
@Test
void createsBoundedLongTimeoutOnlyForExactUnifiedIngestionDraftPath() {
for (URI uri : List.of(
URI.create("http://aixun-dataops/api/dataops/v1/unified-ingestions/draft"),
URI.create("http://aixun-dataops/api/dataops/v1/unified-ingestions/draft?trace=1")
)) {
HttpClientContext context = GatewayHttpClientConfig.createRequestContext(uri, properties);
assertThat(context.getRequestConfig().getConnectionRequestTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(3));
assertThat(context.getRequestConfig().getResponseTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(120));
}
}
@Test
void createsBoundedLongTimeoutOnlyForExactUnifiedIngestionSubmitPath() {
for (URI uri : List.of(
URI.create("http://aixun-dataops/api/dataops/v1/unified-ingestions/submit"),
URI.create("http://aixun-dataops/api/dataops/v1/unified-ingestions/submit?trace=1")
)) {
HttpClientContext context = GatewayHttpClientConfig.createRequestContext(uri, properties);
assertThat(context.getRequestConfig().getConnectionRequestTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(3));
assertThat(context.getRequestConfig().getResponseTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(180));
}
}
@Test
void createsBoundedLongTimeoutOnlyForExactDataSourceConnectionTestBoundary() {
List<URI> connectionTestUris = List.of(
URI.create("http://aixun-integration/api/integration/v1/data-sources/connection-tests/transient"),
URI.create("http://aixun-integration/api/integration/v1/data-sources/1/connection-tests"),
URI.create("http://aixun-integration/api/integration/v1/data-sources/2094725669111885826/connection-tests?trace=1")
);
for (URI uri : connectionTestUris) {
HttpClientContext context = GatewayHttpClientConfig.createRequestContext(uri, properties);
RequestConfig requestConfig = context.getRequestConfig();
assertThat(requestConfig.getConnectionRequestTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(3));
assertThat(requestConfig.getResponseTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(75));
}
}
@Test
void createsLongTimeoutContextOnlyForExactM2CallbackBoundary() {
List<URI> callbackUris = List.of(
URI.create("http://aixun-integration/internal/integration/v1/m2/stages"),
URI.create("http://aixun-integration/internal/integration/v1/m2/stages/openmetadata?runId=1")
);
for (URI uri : callbackUris) {
HttpClientContext context = GatewayHttpClientConfig.createRequestContext(uri, properties);
RequestConfig requestConfig = context.getRequestConfig();
assertThat(requestConfig.getConnectionRequestTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(3));
assertThat(requestConfig.getResponseTimeout().toDuration())
.isEqualTo(Duration.ofSeconds(450));
}
}
@Test
void leavesNormalAndNearMatchUrisOnTheDefaultTimeout() {
List<URI> normalUris = List.of(
URI.create("http://aixun-system/system/user/list"),
URI.create("http://aixun-integration/internal/integration/v1/m2/stagesx"),
URI.create("http://aixun-integration/internal/integration/v1/m2/other"),
URI.create("http://aixun-integration/api/integration/v1/data-sources/not-a-number/connection-tests"),
URI.create("http://aixun-integration/api/integration/v1/data-sources/connection-tests"),
URI.create("http://aixun-integration/api/integration/v1/data-sources//connection-tests"),
URI.create("http://aixun-integration/api/integration/v1/data-sources/1/connection-tests/history"),
URI.create("http://aixun-integration/api/integration/v1/data-sources/1/connection-testsx"),
URI.create("http://aixun-integration/api/integration/v1/data-sources/1/connection-tests/"),
URI.create("http://aixun-dataops/api/dataops/v1/unified-ingestions"),
URI.create("http://aixun-dataops/api/dataops/v1/unified-ingestions/draft/"),
URI.create("http://aixun-dataops/api/dataops/v1/unified-ingestions/draft-extra"),
URI.create("http://aixun-dataops/api/dataops/v1/unified-ingestions/submit/"),
URI.create("http://aixun-dataops/api/dataops/v1/unified-ingestions/submit-extra"),
URI.create("http://aixun-governance/api/governance/v1/metadata-catalog/TABLE/123e4567-e89b-12d3-a456-426614174000/management"),
URI.create("http://aixun-governance/api/governance/v1/standard-adoptions"),
URI.create("http://aixun-integration/"),
URI.create("http://aixun-integration")
);
for (URI uri : normalUris) {
assertThat(GatewayHttpClientConfig.createRequestContext(uri, properties)).isNull();
}
assertThat(GatewayHttpClientConfig.createRequestContext(null, properties)).isNull();
}
}
@@ -0,0 +1,41 @@
package cn.aixunkeji.gateway.handler;
import cn.aixunkeji.common.core.constant.HttpStatus;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.servlet.NoHandlerFoundException;
import static org.assertj.core.api.Assertions.assertThat;
class GatewayExceptionHandlerTest {
@Test
void mapsMissingLocalRouteToSafeNotFound() {
var error = GatewayExceptionHandler.mapError(
new NoHandlerFoundException("GET", "/__missing_route__", HttpHeaders.EMPTY));
assertThat(error.code()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(error.message()).isEqualTo("请求地址不存在");
}
@Test
void mapsUnsupportedMethodToSafeMethodNotAllowed() {
var error = GatewayExceptionHandler.mapError(
new HttpRequestMethodNotSupportedException("TRACE"));
assertThat(error.code()).isEqualTo(HttpStatus.BAD_METHOD);
assertThat(error.message()).isEqualTo("请求方式不支持");
}
@Test
void keepsUnexpectedFailuresAtSafeInternalError() {
var error = GatewayExceptionHandler.mapError(
new IllegalStateException("sensitive internal detail"));
assertThat(error.code()).isEqualTo(HttpStatus.ERROR);
assertThat(error.message())
.isEqualTo("内部服务器错误")
.doesNotContain("sensitive", "IllegalStateException");
}
}