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

constants-configuration.mddocs/

Constants and Configuration

The Constants and Configuration system provides essential constants and configuration values used throughout the Sentinel API Gateway Adapter Common library. These constants define various strategies, modes, and behaviors for gateway flow control and API matching.

Capabilities

SentinelGatewayConstants

Central collection of constants used throughout the gateway adapter system for consistent configuration and behavior.

/**
 * Constants for gateway adapter configuration and behavior
 */
final class SentinelGatewayConstants {
    // Application Type Constants
    
    /** Gateway application type identifier */
    static final int APP_TYPE_GATEWAY = 1;
    
    // Resource Mode Constants
    
    /** Resource identified by route ID */
    static final int RESOURCE_MODE_ROUTE_ID = 0;
    
    /** Resource identified by custom API name */
    static final int RESOURCE_MODE_CUSTOM_API_NAME = 1;
    
    // Parameter Parse Strategy Constants
    
    /** Parse client IP address */
    static final int PARAM_PARSE_STRATEGY_CLIENT_IP = 0;
    
    /** Parse host header */
    static final int PARAM_PARSE_STRATEGY_HOST = 1;
    
    /** Parse arbitrary header */
    static final int PARAM_PARSE_STRATEGY_HEADER = 2;
    
    /** Parse URL parameter */
    static final int PARAM_PARSE_STRATEGY_URL_PARAM = 3;
    
    /** Parse cookie value */
    static final int PARAM_PARSE_STRATEGY_COOKIE = 4;
    
    // URL Matching Strategy Constants
    
    /** Exact match */
    static final int URL_MATCH_STRATEGY_EXACT = 0;
    
    /** Prefix match */
    static final int URL_MATCH_STRATEGY_PREFIX = 1;
    
    /** Regular expression match */
    static final int URL_MATCH_STRATEGY_REGEX = 2;
    
    // Parameter Matching Strategy Constants
    
    /** Exact match */
    static final int PARAM_MATCH_STRATEGY_EXACT = 0;
    
    /** Prefix match */
    static final int PARAM_MATCH_STRATEGY_PREFIX = 1;
    
    /** Regular expression match */
    static final int PARAM_MATCH_STRATEGY_REGEX = 2;
    
    /** Contains match */
    static final int PARAM_MATCH_STRATEGY_CONTAINS = 3;
    
    // Context Constants
    
    /** Default gateway context name */
    static final String GATEWAY_CONTEXT_DEFAULT = "sentinel_gateway_context_default";
    
    /** Gateway context prefix */
    static final String GATEWAY_CONTEXT_PREFIX = "sentinel_gateway_context$$";
    
    /** Gateway route context prefix */
    static final String GATEWAY_CONTEXT_ROUTE_PREFIX = "sentinel_gateway_context$$route$$";
    
    // Parameter Constants
    
    /** Parameter for non-matching requests */
    static final String GATEWAY_NOT_MATCH_PARAM = "$NM";
    
    /** Default parameter marker */
    static final String GATEWAY_DEFAULT_PARAM = "$D";
}

Application Type Configuration

Gateway Application Type

The APP_TYPE_GATEWAY constant identifies applications as gateway services within the Sentinel ecosystem:

// Usage in application configuration
public class GatewayAppConfig {
    static {
        // Mark this application as a gateway
        AppNameUtil.setAppType(SentinelGatewayConstants.APP_TYPE_GATEWAY);
    }
}

Resource Mode Configuration

Resource modes determine how gateway resources are identified and matched:

Route ID Mode (RESOURCE_MODE_ROUTE_ID = 0)

Resources are identified by specific route identifiers from the gateway configuration:

// Route-based flow control
GatewayFlowRule routeRule = new GatewayFlowRule("user-service-route")
    .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID)
    .setGrade(RuleConstant.FLOW_GRADE_QPS)
    .setCount(100);

// Context creation for route-based resources
String routeContext = SentinelGatewayConstants.GATEWAY_CONTEXT_ROUTE_PREFIX + "user-service-route";
ContextUtil.enter(routeContext);

Custom API Name Mode (RESOURCE_MODE_CUSTOM_API_NAME = 1)

Resources are identified by custom API names defined through ApiDefinition:

// API-based flow control
GatewayFlowRule apiRule = new GatewayFlowRule("user-api")
    .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
    .setGrade(RuleConstant.FLOW_GRADE_QPS)
    .setCount(200);

// Must be used with corresponding ApiDefinition
ApiDefinition userApi = new ApiDefinition("user-api")
    .setPredicateItems(Set.of(
        new ApiPathPredicateItem()
            .setPattern("/api/users/**")
            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX)
    ));

Parameter Parse Strategies

These constants define how parameters are extracted from gateway requests for parameter-based flow control:

Client IP Strategy (PARAM_PARSE_STRATEGY_CLIENT_IP = 0)

Extracts the client's IP address:

// IP-based flow control
GatewayParamFlowItem ipParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP);

GatewayFlowRule ipRule = new GatewayFlowRule("api-endpoint")
    .setGrade(RuleConstant.FLOW_GRADE_QPS)
    .setCount(10)  // 10 QPS per IP
    .setParamItem(ipParam);

Host Strategy (PARAM_PARSE_STRATEGY_HOST = 1)

Extracts the Host header value:

// Host-based flow control
GatewayParamFlowItem hostParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HOST);

GatewayFlowRule hostRule = new GatewayFlowRule("multi-tenant-api")
    .setGrade(RuleConstant.FLOW_GRADE_QPS)
    .setCount(500)  // 500 QPS per host
    .setParamItem(hostParam);

Header Strategy (PARAM_PARSE_STRATEGY_HEADER = 2)

Extracts a specific header value (requires fieldName):

// Header-based flow control
GatewayParamFlowItem headerParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
    .setFieldName("X-User-ID");

GatewayFlowRule userRule = new GatewayFlowRule("user-specific-api")
    .setGrade(RuleConstant.FLOW_GRADE_QPS)
    .setCount(50)  // 50 QPS per user
    .setParamItem(headerParam);

URL Parameter Strategy (PARAM_PARSE_STRATEGY_URL_PARAM = 3)

Extracts a URL query parameter value (requires fieldName):

// URL parameter-based flow control
GatewayParamFlowItem urlParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
    .setFieldName("api_key");

GatewayFlowRule apiKeyRule = new GatewayFlowRule("api-service")
    .setGrade(RuleConstant.FLOW_GRADE_QPS)
    .setCount(1000)  // 1000 QPS per API key
    .setParamItem(urlParam);

Cookie Strategy (PARAM_PARSE_STRATEGY_COOKIE = 4)

Extracts a cookie value (requires fieldName):

// Cookie-based flow control
GatewayParamFlowItem cookieParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_COOKIE)
    .setFieldName("session_id");

GatewayFlowRule sessionRule = new GatewayFlowRule("session-api")
    .setGrade(RuleConstant.FLOW_GRADE_QPS)
    .setCount(20)  // 20 QPS per session
    .setParamItem(cookieParam);

URL Matching Strategies

These constants define how URL patterns are matched against incoming requests:

Exact Match (URL_MATCH_STRATEGY_EXACT = 0)

Requires exact string match:

// Exact path matching
ApiPathPredicateItem exactMatch = new ApiPathPredicateItem()
    .setPattern("/api/users/profile")
    .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_EXACT);

// Only matches exactly "/api/users/profile"

Prefix Match (URL_MATCH_STRATEGY_PREFIX = 1)

Matches any URL starting with the pattern:

// Prefix matching (most common)
ApiPathPredicateItem prefixMatch = new ApiPathPredicateItem()
    .setPattern("/api/users")
    .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX);

// Matches "/api/users", "/api/users/123", "/api/users/profile", etc.

Regex Match (URL_MATCH_STRATEGY_REGEX = 2)

Uses regular expression matching:

// Regex matching for complex patterns
ApiPathPredicateItem regexMatch = new ApiPathPredicateItem()
    .setPattern("/api/users/\\d+/orders")
    .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_REGEX);

// Matches "/api/users/123/orders", "/api/users/456/orders", etc.

Parameter Matching Strategies

These constants define how parameter values are matched against patterns:

Exact Match (PARAM_MATCH_STRATEGY_EXACT = 0)

Requires exact string match:

// Exact parameter matching
GatewayParamFlowItem exactParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
    .setFieldName("User-Type")
    .setPattern("premium")
    .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT);

// Only matches when User-Type header is exactly "premium"

Prefix Match (PARAM_MATCH_STRATEGY_PREFIX = 1)

Matches parameters starting with the pattern:

// Prefix parameter matching
GatewayParamFlowItem prefixParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
    .setFieldName("API-Key")
    .setPattern("dev_")
    .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_PREFIX);

// Matches "dev_123", "dev_test", etc.

Regex Match (PARAM_MATCH_STRATEGY_REGEX = 2)

Uses regular expression matching:

// Regex parameter matching
GatewayParamFlowItem regexParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
    .setFieldName("User-ID")
    .setPattern("user_\\d+")
    .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX);

// Matches "user_123", "user_456", etc.

Contains Match (PARAM_MATCH_STRATEGY_CONTAINS = 3)

Matches parameters containing the pattern:

// Contains parameter matching
GatewayParamFlowItem containsParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
    .setFieldName("Authorization")
    .setPattern("Bearer")
    .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS);

// Matches "Bearer token123", "JWT Bearer abc", etc.

Context Configuration

Gateway contexts are used to organize and isolate different types of gateway traffic:

Default Gateway Context

// Use default gateway context
ContextUtil.enter(SentinelGatewayConstants.GATEWAY_CONTEXT_DEFAULT);

// Context name: "sentinel_gateway_context_default"

Custom Gateway Context

// Create custom gateway context
String customContext = SentinelGatewayConstants.GATEWAY_CONTEXT_PREFIX + "api-v1";
ContextUtil.enter(customContext);

// Context name: "sentinel_gateway_context$$api-v1"

Route-Specific Context

// Create route-specific context
String routeContext = SentinelGatewayConstants.GATEWAY_CONTEXT_ROUTE_PREFIX + "payment-service";
ContextUtil.enter(routeContext);

// Context name: "sentinel_gateway_context$$route$$payment-service"

Special Parameter Values

Non-Matching Parameter (GATEWAY_NOT_MATCH_PARAM = "$NM")

Used internally when parameter extraction fails or doesn't match any pattern:

// Internal usage - indicates parameter didn't match any pattern
// This constant is used by the parameter parsing system automatically

Default Parameter (GATEWAY_DEFAULT_PARAM = "$D")

Used internally as a default parameter marker:

// Internal usage - default parameter value
// This constant is used by the parameter parsing system automatically

Configuration Best Practices

Consistent Strategy Usage

// Use consistent matching strategies within related rules
public class ConsistentMatchingExample {
    public void setupConsistentRules() {
        // All user-related APIs use prefix matching
        ApiDefinition userApi = new ApiDefinition("user-api")
            .setPredicateItems(Set.of(
                new ApiPathPredicateItem()
                    .setPattern("/api/users")
                    .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX),
                new ApiPathPredicateItem()
                    .setPattern("/api/user-profile")
                    .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX)
            ));
    }
}

Performance Considerations

public class PerformanceOptimizedConfig {
    public void setupOptimizedRules() {
        // Prefer exact/prefix matching over regex for better performance
        ApiPathPredicateItem fastMatch = new ApiPathPredicateItem()
            .setPattern("/api/health")
            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_EXACT);  // Fast
        
        // Use regex sparingly and cache patterns
        ApiPathPredicateItem complexMatch = new ApiPathPredicateItem()
            .setPattern("/api/users/\\d+")
            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_REGEX);  // Slower
        
        // Pre-cache regex patterns
        GatewayRegexCache.addRegexPattern("/api/users/\\d+");
    }
}

Configuration Validation

public class ConfigurationValidator {
    public boolean validateConfiguration(GatewayFlowRule rule) {
        // Validate resource mode
        if (rule.getResourceMode() != SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID && 
            rule.getResourceMode() != SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME) {
            return false;
        }
        
        // Validate parameter item if present
        GatewayParamFlowItem paramItem = rule.getParamItem();
        if (paramItem != null) {
            int strategy = paramItem.getParseStrategy();
            if (strategy < SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP || 
                strategy > SentinelGatewayConstants.PARAM_PARSE_STRATEGY_COOKIE) {
                return false;
            }
            
            // Check required field name for certain strategies
            if (strategy == SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER ||
                strategy == SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM ||
                strategy == SentinelGatewayConstants.PARAM_PARSE_STRATEGY_COOKIE) {
                if (paramItem.getFieldName() == null || paramItem.getFieldName().isEmpty()) {
                    return false;
                }
            }
        }
        
        return true;
    }
}

Best Practices

  1. Use appropriate matching strategies - exact for specific endpoints, prefix for API groups, regex sparingly
  2. Validate constants usage - ensure correct constant values are used for strategies and modes
  3. Pre-cache regex patterns using GatewayRegexCache for better performance
  4. Use consistent context naming following the established prefix patterns
  5. Prefer simpler matching strategies (exact/prefix) over complex ones (regex) for performance
  6. Document custom constants if extending the system with additional configuration values
  7. Validate configuration programmatically before applying rules in production
  8. Use meaningful resource names that align with your gateway routing configuration

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