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

gateway-flow-rules.mddocs/

Gateway Flow Rules

The Gateway Flow Rules system provides comprehensive flow control capabilities for API gateways, supporting QPS/thread-based limiting, burst control, and parameter-based flow control. Rules are automatically converted to Sentinel's core flow control rules for seamless integration.

Capabilities

GatewayFlowRule

Core configuration class for gateway flow control rules with support for various control behaviors and parameter-based limiting.

/**
 * Configuration for gateway flow control rules
 */
class GatewayFlowRule {
    /** Default constructor */
    GatewayFlowRule();
    
    /** Constructor with resource name */
    GatewayFlowRule(String resource);
    
    /** Get the resource name (route ID or API name) */
    String getResource();
    
    /** Set the resource name (fluent interface) */
    GatewayFlowRule setResource(String resource);
    
    /** Get the resource mode (route ID or custom API name) */
    int getResourceMode();
    
    /** Set the resource mode (fluent interface) */
    GatewayFlowRule setResourceMode(int resourceMode);
    
    /** Get the flow control grade (QPS or thread count) */
    int getGrade();
    
    /** Set the flow control grade (fluent interface) */
    GatewayFlowRule setGrade(int grade);
    
    /** Get the threshold count for flow control */
    double getCount();
    
    /** Set the threshold count (fluent interface) */
    GatewayFlowRule setCount(double count);
    
    /** Get the time interval in seconds for counting */
    long getIntervalSec();
    
    /** Set the time interval in seconds (fluent interface) */
    GatewayFlowRule setIntervalSec(long intervalSec);
    
    /** Get the control behavior when threshold is exceeded */
    int getControlBehavior();
    
    /** Set the control behavior (fluent interface) */
    GatewayFlowRule setControlBehavior(int controlBehavior);
    
    /** Get the burst size for traffic bursts */
    int getBurst();
    
    /** Set the burst size (fluent interface) */
    GatewayFlowRule setBurst(int burst);
    
    /** Get the maximum queuing timeout in milliseconds */
    int getMaxQueueingTimeoutMs();
    
    /** Set the maximum queuing timeout (fluent interface) */
    GatewayFlowRule setMaxQueueingTimeoutMs(int maxQueueingTimeoutMs);
    
    /** Get the parameter flow item for parameter-based control */
    GatewayParamFlowItem getParamItem();
    
    /** Set the parameter flow item (fluent interface) */
    GatewayFlowRule setParamItem(GatewayParamFlowItem paramItem);
}

Usage Examples:

// Basic QPS limiting
GatewayFlowRule qpsRule = new GatewayFlowRule("user-api")
    .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
    .setGrade(RuleConstant.FLOW_GRADE_QPS)
    .setCount(100)  // 100 QPS limit
    .setIntervalSec(1);

// Thread-based limiting with burst support
GatewayFlowRule threadRule = new GatewayFlowRule("order-processing")
    .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID)
    .setGrade(RuleConstant.FLOW_GRADE_THREAD)
    .setCount(10)   // 10 concurrent threads
    .setBurst(5);   // Allow up to 5 additional threads during bursts

// Rate limiting with queueing
GatewayFlowRule rateLimitRule = new GatewayFlowRule("payment-api")
    .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
    .setGrade(RuleConstant.FLOW_GRADE_QPS)
    .setCount(50)
    .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
    .setMaxQueueingTimeoutMs(2000);  // Queue for up to 2 seconds

GatewayParamFlowItem

Configuration for parameter-based flow control, enabling fine-grained control based on request parameters.

/**
 * Configuration for parameter-based flow control
 */
class GatewayParamFlowItem {
    /** Get the parameter parsing strategy */
    int getParseStrategy();
    
    /** Set the parameter parsing strategy (fluent interface) */
    GatewayParamFlowItem setParseStrategy(int parseStrategy);
    
    /** Get the field name for header/URL param/cookie extraction */
    String getFieldName();
    
    /** Set the field name (fluent interface) */
    GatewayParamFlowItem setFieldName(String fieldName);
    
    /** Get the matching pattern for parameter values */
    String getPattern();
    
    /** Set the matching pattern (fluent interface) */
    GatewayParamFlowItem setPattern(String pattern);
    
    /** Get the matching strategy for parameter values */
    int getMatchStrategy();
    
    /** Set the matching strategy (fluent interface) */
    GatewayParamFlowItem setMatchStrategy(int matchStrategy);
}

Usage Examples:

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

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

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

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

// URL parameter with pattern matching
GatewayParamFlowItem apiKeyParam = new GatewayParamFlowItem()
    .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
    .setFieldName("api_key")
    .setPattern("premium_.*")  // Only apply to premium API keys
    .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX);

GatewayFlowRule premiumRule = new GatewayFlowRule("premium-api")
    .setGrade(RuleConstant.FLOW_GRADE_QPS)
    .setCount(1000)  // Higher limits for premium users
    .setParamItem(apiKeyParam);

GatewayRuleManager

Manager class for loading, validating, and managing gateway flow rules with automatic conversion to Sentinel parameter rules.

/**
 * Manager for gateway flow rules with validation and conversion
 */
final class GatewayRuleManager {
    /** Register a property for rule updates */
    static void register2Property(SentinelProperty<Set<GatewayFlowRule>> property);
    
    /** Load gateway rules, replacing existing ones */
    static boolean loadRules(Set<GatewayFlowRule> rules);
    
    /** Get all currently loaded gateway rules */
    static Set<GatewayFlowRule> getRules();
    
    /** Get rules for a specific resource */
    static Set<GatewayFlowRule> getRulesForResource(String resourceName);
    
    /** Get converted parameter rules for internal use */
    static List<ParamFlowRule> getConvertedParamRules(String resourceName);
    
    /** Validate if a gateway rule is properly configured */
    static boolean isValidRule(GatewayFlowRule rule);
}

Usage Examples:

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.*;
import java.util.Set;

// Create multiple gateway rules
Set<GatewayFlowRule> rules = Set.of(
    // API-level QPS limiting
    new GatewayFlowRule("user-api")
        .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
        .setGrade(RuleConstant.FLOW_GRADE_QPS)
        .setCount(200),
    
    // Route-level with parameter control
    new GatewayFlowRule("payment-route")
        .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID)
        .setGrade(RuleConstant.FLOW_GRADE_QPS)
        .setCount(50)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)),
    
    // Thread-based limiting
    new GatewayFlowRule("processing-api")
        .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
        .setGrade(RuleConstant.FLOW_GRADE_THREAD)
        .setCount(20)
        .setBurst(10)
);

// Load rules
boolean loaded = GatewayRuleManager.loadRules(rules);

// Retrieve rules for specific resources
Set<GatewayFlowRule> userApiRules = GatewayRuleManager.getRulesForResource("user-api");

// Get all rules
Set<GatewayFlowRule> allRules = GatewayRuleManager.getRules();

// Validate individual rule
GatewayFlowRule testRule = new GatewayFlowRule("test")
    .setGrade(RuleConstant.FLOW_GRADE_QPS)
    .setCount(100);
boolean isValid = GatewayRuleManager.isValidRule(testRule);

Control Behaviors

Gateway flow rules support different control behaviors from Sentinel's RuleConstant:

  • CONTROL_BEHAVIOR_DEFAULT (0): Direct rejection when threshold exceeded
  • CONTROL_BEHAVIOR_WARM_UP (1): Gradual warm-up period for traffic ramp-up
  • CONTROL_BEHAVIOR_RATE_LIMITER (2): Rate limiting with request queueing
  • CONTROL_BEHAVIOR_WARM_UP_RATE_LIMITER (3): Combination of warm-up and rate limiting

Resource Modes

Gateway rules can target different types of resources:

  • RESOURCE_MODE_ROUTE_ID (0): Target specific gateway routes
  • RESOURCE_MODE_CUSTOM_API_NAME (1): Target API groups defined by ApiDefinition

Parameter Parse Strategies

Parameter-based flow control supports multiple extraction strategies:

  • CLIENT_IP (0): Extract client IP address
  • HOST (1): Extract host header
  • HEADER (2): Extract arbitrary request header (requires fieldName)
  • URL_PARAM (3): Extract URL query parameter (requires fieldName)
  • COOKIE (4): Extract cookie value (requires fieldName)

Parameter Matching Strategies

When using patterns with parameter flow items:

  • EXACT (0): Exact string match
  • PREFIX (1): Prefix-based matching
  • REGEX (2): Regular expression matching
  • CONTAINS (3): Substring matching

Rule Validation

Rules are automatically validated when loaded. A rule is considered invalid if:

  • Resource name is null or empty
  • Resource mode is negative
  • Grade is negative
  • Count is negative
  • Burst is negative
  • Control behavior is negative
  • Interval is zero or negative
  • Rate limiter control behavior with negative queuing timeout
  • Parameter item with invalid parse strategy or missing required field name

Best Practices

  1. Start with simple QPS rules before adding parameter-based controls
  2. Use appropriate resource modes - API names for grouped endpoints, route IDs for specific routes
  3. Configure burst sizes for handling traffic spikes gracefully
  4. Use rate limiting with queueing for APIs that can tolerate slight delays
  5. Monitor parameter rule performance as they have higher overhead than simple rules
  6. Validate rules using isValidRule() before loading in production
  7. Use regex patterns sparingly in parameter matching for performance reasons

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