CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-alibaba-csp--sentinel-api-gateway-adapter-common

Common abstraction module for API gateway flow control in Sentinel providing GatewayFlowRule and ApiDefinition for gateway-specific traffic management.

Pending
Overview
Eval results
Files

parameter-processing.mddocs/

Parameter Processing

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.

Capabilities

RequestItemParser

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;
    }
}

GatewayParamParser

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)

ConfigurableRequestItemParser

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);

GatewayRegexCache

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();

Parameter Extraction Strategies

The parameter processing system supports five extraction strategies defined in SentinelGatewayConstants:

Client IP (Strategy 0)

Extracts the client's IP address from the request.

GatewayParamFlowItem ipParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP);

Host (Strategy 1)

Extracts the Host header from the request.

GatewayParamFlowItem hostParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HOST);

Header (Strategy 2)

Extracts a specific header value (requires fieldName).

GatewayParamFlowItem headerParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
    .setFieldName("X-User-ID");

URL Parameter (Strategy 3)

Extracts a specific URL query parameter (requires fieldName).

GatewayParamFlowItem urlParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
    .setFieldName("api_key");

Cookie (Strategy 4)

Extracts a specific cookie value (requires fieldName).

GatewayParamFlowItem cookieParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_COOKIE)
    .setFieldName("session_id");

Parameter Matching

Once parameters are extracted, they can be matched against patterns using different strategies:

Exact Match (Strategy 0)

paramItem.setPattern("premium_user")
    .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT);

Prefix Match (Strategy 1)

paramItem.setPattern("admin_")
    .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_PREFIX);

Regex Match (Strategy 2)

paramItem.setPattern("user_\\d+")
    .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX);

Contains Match (Strategy 3)

paramItem.setPattern("premium")
    .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS);

Integration Example

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 otherwise

Best Practices

  1. Implement RequestItemParser appropriately for your gateway framework
  2. Use ConfigurableRequestItemParser for complex extraction logic
  3. Cache regex patterns using GatewayRegexCache for better performance
  4. Handle null values gracefully in parameter extraction
  5. Consider proxy headers when extracting client IP addresses
  6. Use appropriate matching strategies - exact for simple values, regex for complex patterns
  7. Pre-validate regex patterns before using them in production
  8. Monitor parameter extraction performance as it adds overhead to request processing

Install with Tessl CLI

npx tessl i tessl/maven-com-alibaba-csp--sentinel-api-gateway-adapter-common

docs

api-definitions.md

command-handlers.md

constants-configuration.md

gateway-flow-rules.md

index.md

parameter-processing.md

sentinel-integration.md

tile.json