Common abstraction module for API gateway flow control in Sentinel providing GatewayFlowRule and ApiDefinition for gateway-specific traffic management.
—
The Parameter Processing system provides a flexible framework for extracting and processing parameters from gateway requests to enable parameter-based flow control. It supports multiple extraction strategies including client IP, headers, URL parameters, and cookies.
Core interface for parsing request items from gateway requests, designed to be implemented for different gateway frameworks.
/**
* Interface for parsing request items from gateway requests
* @param <T> Type of request object (e.g., HttpServletRequest, ServerHttpRequest)
*/
interface RequestItemParser<T> {
/** Extract the request path */
String getPath(T request);
/** Extract the remote address (client IP) */
String getRemoteAddress(T request);
/** Extract a specific header value */
String getHeader(T request, String key);
/** Extract a URL query parameter value */
String getUrlParam(T request, String paramName);
/** Extract a cookie value */
String getCookieValue(T request, String cookieName);
}Usage Examples:
// Example implementation for Spring WebFlux
public class WebFluxRequestItemParser implements RequestItemParser<ServerHttpRequest> {
@Override
public String getPath(ServerHttpRequest request) {
return request.getURI().getPath();
}
@Override
public String getRemoteAddress(ServerHttpRequest request) {
return request.getRemoteAddress() != null ?
request.getRemoteAddress().getAddress().getHostAddress() : null;
}
@Override
public String getHeader(ServerHttpRequest request, String key) {
return request.getHeaders().getFirst(key);
}
@Override
public String getUrlParam(ServerHttpRequest request, String paramName) {
return request.getQueryParams().getFirst(paramName);
}
@Override
public String getCookieValue(ServerHttpRequest request, String cookieName) {
HttpCookie cookie = request.getCookies().getFirst(cookieName);
return cookie != null ? cookie.getValue() : null;
}
}
// Example implementation for Servlet API
public class ServletRequestItemParser implements RequestItemParser<HttpServletRequest> {
@Override
public String getPath(HttpServletRequest request) {
return request.getRequestURI();
}
@Override
public String getRemoteAddress(HttpServletRequest request) {
return request.getRemoteAddr();
}
@Override
public String getHeader(HttpServletRequest request, String key) {
return request.getHeader(key);
}
@Override
public String getUrlParam(HttpServletRequest request, String paramName) {
return request.getParameter(paramName);
}
@Override
public String getCookieValue(HttpServletRequest request, String cookieName) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
return cookie.getValue();
}
}
}
return null;
}
}Parser for extracting parameters from gateway requests based on gateway flow rules for parameter-based flow control.
/**
* Parser for extracting parameters from gateway requests based on rules
* @param <T> Type of request object
*/
class GatewayParamParser<T> {
/** Constructor with request item parser */
GatewayParamParser(RequestItemParser<T> requestItemParser);
/**
* Parse parameters for a specific resource based on matching rules
* @param resource The resource name to parse parameters for
* @param request The gateway request object
* @param rulePredicate Predicate to filter applicable rules
* @return Array of parsed parameter values
*/
Object[] parseParameterFor(String resource, T request, Predicate<GatewayFlowRule> rulePredicate);
}Usage Examples:
// Create parser with request item parser
RequestItemParser<HttpServletRequest> itemParser = new ServletRequestItemParser();
GatewayParamParser<HttpServletRequest> paramParser = new GatewayParamParser<>(itemParser);
// Parse parameters for a specific resource
HttpServletRequest request = // ... get request
Object[] params = paramParser.parseParameterFor(
"user-api",
request,
rule -> rule.getParamItem() != null // Only rules with parameter items
);
// The returned array contains extracted parameter values based on the rules
// For example, if rules extract client IP and user ID header:
// params[0] might be "192.168.1.100" (client IP)
// params[1] might be "user123" (X-User-ID header value)Enhanced request item parser that allows custom extractors to be registered for specific request attributes.
/**
* Configurable parser with custom extractors for request items
* @param <T> Type of request object
*/
class ConfigurableRequestItemParser<T> implements RequestItemParser<T> {
/** Constructor with delegate parser */
ConfigurableRequestItemParser(RequestItemParser<T> delegate);
// RequestItemParser interface methods
String getPath(T request);
String getRemoteAddress(T request);
String getHeader(T request, String key);
String getUrlParam(T request, String paramName);
String getCookieValue(T request, String cookieName);
// Extractor registration methods
/** Add custom path extractor (fluent interface) */
ConfigurableRequestItemParser<T> addPathExtractor(Function<T, String> extractor);
/** Add custom remote address extractor (fluent interface) */
ConfigurableRequestItemParser<T> addRemoteAddressExtractor(Function<T, String> extractor);
/** Add custom header extractor (fluent interface) */
ConfigurableRequestItemParser<T> addHeaderExtractor(BiFunction<T, String, String> extractor);
/** Add custom URL parameter extractor (fluent interface) */
ConfigurableRequestItemParser<T> addUrlParamExtractor(BiFunction<T, String, String> extractor);
/** Add custom cookie value extractor (fluent interface) */
ConfigurableRequestItemParser<T> addCookieValueExtractor(BiFunction<T, String, String> extractor);
}Usage Examples:
// Create configurable parser with base implementation
RequestItemParser<ServerHttpRequest> baseParser = new WebFluxRequestItemParser();
ConfigurableRequestItemParser<ServerHttpRequest> configurableParser =
new ConfigurableRequestItemParser<>(baseParser);
// Add custom extractors for special cases
configurableParser
.addRemoteAddressExtractor(request -> {
// Custom logic to extract real client IP from proxy headers
String xForwardedFor = request.getHeaders().getFirst("X-Forwarded-For");
if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
return xForwardedFor.split(",")[0].trim();
}
String xRealIp = request.getHeaders().getFirst("X-Real-IP");
if (xRealIp != null && !xRealIp.isEmpty()) {
return xRealIp;
}
// Fall back to default behavior
return baseParser.getRemoteAddress(request);
})
.addHeaderExtractor((request, key) -> {
// Custom header extraction with case-insensitive lookup
return request.getHeaders().entrySet().stream()
.filter(entry -> entry.getKey().equalsIgnoreCase(key))
.findFirst()
.map(entry -> entry.getValue().get(0))
.orElse(null);
});
// Use the configurable parser
GatewayParamParser<ServerHttpRequest> paramParser =
new GatewayParamParser<>(configurableParser);Cache for compiled regex patterns used in parameter matching to improve performance.
/**
* Cache for compiled regex patterns used in gateway rules
*/
final class GatewayRegexCache {
/** Get compiled pattern from cache */
static Pattern getRegexPattern(String pattern);
/** Add pattern to cache, returns true if successfully compiled */
static boolean addRegexPattern(String pattern);
/** Clear all cached patterns */
static void clear();
}Usage Examples:
// Pre-compile and cache regex patterns
boolean added = GatewayRegexCache.addRegexPattern("user_\\d+");
// Retrieve compiled pattern (returns null if not found or invalid)
Pattern pattern = GatewayRegexCache.getRegexPattern("user_\\d+");
if (pattern != null) {
boolean matches = pattern.matcher("user_123").matches();
}
// Clear cache when patterns change
GatewayRegexCache.clear();The parameter processing system supports five extraction strategies defined in SentinelGatewayConstants:
Extracts the client's IP address from the request.
GatewayParamFlowItem ipParam = new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP);Extracts the Host header from the request.
GatewayParamFlowItem hostParam = new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HOST);Extracts a specific header value (requires fieldName).
GatewayParamFlowItem headerParam = new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
.setFieldName("X-User-ID");Extracts a specific URL query parameter (requires fieldName).
GatewayParamFlowItem urlParam = new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
.setFieldName("api_key");Extracts a specific cookie value (requires fieldName).
GatewayParamFlowItem cookieParam = new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_COOKIE)
.setFieldName("session_id");Once parameters are extracted, they can be matched against patterns using different strategies:
paramItem.setPattern("premium_user")
.setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT);paramItem.setPattern("admin_")
.setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_PREFIX);paramItem.setPattern("user_\\d+")
.setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX);paramItem.setPattern("premium")
.setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS);Complete example showing parameter processing integration:
// 1. Create request item parser for your gateway framework
RequestItemParser<HttpServletRequest> parser = new ServletRequestItemParser();
// 2. Create parameter parser
GatewayParamParser<HttpServletRequest> paramParser = new GatewayParamParser<>(parser);
// 3. Define parameter-based flow rule
GatewayParamFlowItem userParam = new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
.setFieldName("X-User-Type")
.setPattern("premium")
.setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT);
GatewayFlowRule rule = new GatewayFlowRule("api-endpoint")
.setGrade(RuleConstant.FLOW_GRADE_QPS)
.setCount(1000) // Higher limit for premium users
.setParamItem(userParam);
// 4. Load rule
GatewayRuleManager.loadRules(Set.of(rule));
// 5. In request processing
HttpServletRequest request = // ... get request
Object[] params = paramParser.parseParameterFor("api-endpoint", request, r -> true);
// params[0] contains "premium" if X-User-Type header matches, null otherwiseInstall with Tessl CLI
npx tessl i tessl/maven-com-alibaba-csp--sentinel-api-gateway-adapter-common