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

sentinel-integration.mddocs/

Sentinel Integration

The Sentinel Integration system provides components for embedding gateway flow control into Sentinel's processing chain using the slot-based architecture. This enables seamless integration with Sentinel's core flow control, circuit breaking, and monitoring capabilities.

Capabilities

GatewayFlowSlot

Core Sentinel slot for gateway parameter flow checking, integrated into Sentinel's processing chain with high priority.

/**
 * Sentinel slot for gateway parameter flow checking
 * Integrated with Sentinel's slot chain at order -4000 (high priority)
 */
@Spi(order = -4000)
class GatewayFlowSlot extends AbstractLinkedProcessorSlot<DefaultNode> {
    /**
     * Main entry point for flow control checking
     * @param context Sentinel context containing request information
     * @param resource Resource wrapper identifying the protected resource
     * @param node Default node for metrics collection
     * @param count Request count (usually 1)
     * @param prioritized Whether this is a prioritized request
     * @param args Additional arguments including parsed parameters
     * @throws Throwable When flow control blocks the request
     */
    void entry(Context context, ResourceWrapper resource, DefaultNode node, int count, 
               boolean prioritized, Object... args) throws Throwable;
    
    /**
     * Exit point called after request processing
     * @param context Sentinel context
     * @param resourceWrapper Resource wrapper
     * @param count Request count
     * @param args Additional arguments
     */
    void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args);
}

Usage Examples:

The GatewayFlowSlot is automatically integrated into Sentinel's slot chain through the SPI mechanism. It doesn't require direct instantiation but is configured through the slot chain builder:

// GatewayFlowSlot is automatically loaded and positioned in the slot chain
// when Sentinel initializes due to the @Spi annotation

// The slot processes gateway-specific flow control rules and converts them
// to standard Sentinel parameter flow rules for processing

// Example of how it's used internally:
public class GatewayEntryExample {
    public void processRequest(String resource, HttpServletRequest request) {
        Entry entry = null;
        try {
            // Parse parameters for gateway flow control
            Object[] params = extractParameters(request);
            
            // Create Sentinel entry - GatewayFlowSlot will be invoked automatically
            entry = SphU.entry(resource, EntryType.IN, 1, params);
            
            // Process the request
            handleRequest(request);
            
        } catch (BlockException e) {
            // Handle flow control blocking
            handleBlockedException(e);
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
    }
}

GatewaySlotChainBuilder (Deprecated)

Legacy slot chain builder for gateway-specific slot chain construction.

/**
 * Legacy slot chain builder (deprecated since 1.7.2)
 * Use Sentinel's default slot chain builder instead
 */
@Deprecated
class GatewaySlotChainBuilder extends DefaultSlotChainBuilder {
    // Implementation details omitted as this class is deprecated
}

Migration Note:

The GatewaySlotChainBuilder is deprecated since version 1.7.2. Instead of using a custom slot chain builder, the GatewayFlowSlot is now automatically integrated into the default slot chain through the SPI mechanism.

// OLD (deprecated) approach:
// SlotChainProvider.setSlotChainBuilder(new GatewaySlotChainBuilder());

// NEW approach:
// No explicit configuration needed - GatewayFlowSlot is automatically loaded
// through @Spi annotation when Sentinel initializes

Integration with Sentinel's Processing Chain

The gateway integration follows Sentinel's standard slot-based processing model:

Slot Chain Order

The GatewayFlowSlot is positioned with order -4000, meaning it executes early in the slot chain:

  1. GatewayFlowSlot (-4000) - Gateway-specific parameter flow control
  2. NodeSelectorSlot (-10000) - Resource node selection
  3. ClusterBuilderSlot (-9000) - Cluster node building
  4. LogSlot (-8000) - Request logging
  5. StatisticSlot (-7000) - Metrics collection
  6. ParamFlowSlot (-6000) - Parameter flow control
  7. SystemSlot (-5000) - System protection
  8. AuthoritySlot (-4000) - Authority control
  9. FlowSlot (-2000) - Standard flow control
  10. DegradeSlot (-1000) - Circuit breaker

Context and Resource Handling

The gateway integration uses Sentinel's context system for resource identification:

// Context names follow gateway-specific patterns
public static final String GATEWAY_CONTEXT_DEFAULT = "sentinel_gateway_context_default";
public static final String GATEWAY_CONTEXT_PREFIX = "sentinel_gateway_context$$";
public static final String GATEWAY_CONTEXT_ROUTE_PREFIX = "sentinel_gateway_context$$route$$";

Usage Examples:

// Gateway contexts are typically created automatically, but can be customized:

// Default gateway context
ContextUtil.enter(SentinelGatewayConstants.GATEWAY_CONTEXT_DEFAULT);

// Route-specific context
String routeContext = SentinelGatewayConstants.GATEWAY_CONTEXT_ROUTE_PREFIX + "user-service";
ContextUtil.enter(routeContext);

// Custom API context
String apiContext = SentinelGatewayConstants.GATEWAY_CONTEXT_PREFIX + "user-api";
ContextUtil.enter(apiContext);

Parameter Processing Integration

The gateway integration automatically handles parameter extraction and processing:

Parameter Extraction Flow

  1. Rule Matching: Gateway flow rules are matched against the current resource
  2. Parameter Extraction: Parameters are extracted based on rule configuration
  3. Rule Conversion: Gateway rules are converted to standard Sentinel parameter rules
  4. Flow Control: Standard Sentinel parameter flow control is applied
// Example of parameter processing integration
public class GatewayParameterIntegration {
    private final GatewayParamParser<HttpServletRequest> paramParser;
    
    public void processGatewayRequest(String resource, HttpServletRequest request) {
        // Extract parameters based on gateway rules
        Object[] params = paramParser.parseParameterFor(resource, request, rule -> true);
        
        Entry entry = null;
        try {
            // Pass parameters to Sentinel - GatewayFlowSlot will process them
            entry = SphU.entry(resource, EntryType.IN, 1, params);
            
            // Process request
            processRequest(request);
            
        } catch (ParamFlowException e) {
            // Handle parameter-based flow control
            handleParameterFlowControl(e);
        } catch (FlowException e) {
            // Handle general flow control
            handleFlowControl(e);
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
    }
}

Rule Conversion and Management

Gateway rules are automatically converted to standard Sentinel rules for processing:

Conversion Process

  1. Gateway Rules: Defined using GatewayFlowRule with gateway-specific parameters
  2. Parameter Rules: Converted to ParamFlowRule for parameter-based control
  3. Flow Rules: Simple rules converted to standard FlowRule objects
  4. Metrics Storage: Parameter metrics stored using Sentinel's parameter metric system
// Example of rule conversion (handled automatically)
public class RuleConversionExample {
    public void demonstrateConversion() {
        // Gateway rule with parameter control
        GatewayFlowRule gatewayRule = new GatewayFlowRule("user-api")
            .setGrade(RuleConstant.FLOW_GRADE_QPS)
            .setCount(100)
            .setParamItem(new GatewayParamFlowItem()
                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP));
        
        // Load gateway rule - conversion happens automatically
        GatewayRuleManager.loadRules(Set.of(gatewayRule));
        
        // Retrieve converted parameter rules (for monitoring/debugging)
        List<ParamFlowRule> convertedRules = GatewayRuleManager.getConvertedParamRules("user-api");
        
        // The converted rules are automatically used by Sentinel's parameter flow control
    }
}

Error Handling and Exceptions

Gateway integration handles various Sentinel exceptions:

Exception Types

// Parameter-based flow control exceptions
catch (ParamFlowException e) {
    // Triggered when parameter flow rules are violated
    // e.g., too many requests from same IP, user, etc.
    return buildRateLimitResponse("Parameter limit exceeded", 429);
}

// General flow control exceptions  
catch (FlowException e) {
    // Triggered when general flow rules are violated
    // e.g., QPS limit exceeded
    return buildRateLimitResponse("Rate limit exceeded", 429);
}

// System protection exceptions
catch (SystemBlockException e) {
    // Triggered when system protection rules are violated
    return buildRateLimitResponse("System overloaded", 503);
}

// Authority control exceptions
catch (AuthorityException e) {
    // Triggered when authority rules are violated
    return buildRateLimitResponse("Access denied", 403);
}

// Circuit breaker exceptions
catch (DegradeException e) {
    // Triggered when circuit breaker is open
    return buildRateLimitResponse("Service unavailable", 503);
}

Monitoring and Metrics

Gateway integration supports comprehensive monitoring through Sentinel's metrics system:

Metrics Collection

// Metrics are automatically collected for gateway resources
public class GatewayMonitoring {
    public void displayMetrics(String resource) {
        // Get parameter metrics for gateway resource
        ParameterMetric paramMetric = ParameterMetricStorage.getParamMetricForResource(resource);
        if (paramMetric != null) {
            // Access parameter-specific metrics
            // e.g., QPS per IP, per user, etc.
        }
        
        // Get standard resource metrics
        ClusterNode clusterNode = ClusterBuilderSlot.getClusterNode(resource);
        if (clusterNode != null) {
            long totalQps = clusterNode.totalQps();
            long passQps = clusterNode.passQps();
            long blockQps = clusterNode.blockQps();
            
            System.out.printf("Resource: %s, Total: %d, Pass: %d, Block: %d%n", 
                resource, totalQps, passQps, blockQps);
        }
    }
}

Best Practices

  1. Use appropriate context names for different gateway resources
  2. Monitor converted parameter rules to understand actual flow control behavior
  3. Handle all Sentinel exception types appropriately in gateway responses
  4. Configure slot chain properly - avoid using deprecated GatewaySlotChainBuilder
  5. Monitor parameter metrics for insights into parameter-based flow patterns
  6. Use consistent resource naming across gateway rules and API definitions
  7. Test exception handling to ensure proper rate limit responses
  8. Consider performance impact of parameter extraction in high-traffic scenarios
  9. Use resource hierarchies effectively for better monitoring and control granularity
  10. Integrate with Sentinel dashboard for real-time monitoring and rule management

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