0
# Parameter Processing
1
2
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.
3
4
## Capabilities
5
6
### RequestItemParser
7
8
Core interface for parsing request items from gateway requests, designed to be implemented for different gateway frameworks.
9
10
```java { .api }
11
/**
12
* Interface for parsing request items from gateway requests
13
* @param <T> Type of request object (e.g., HttpServletRequest, ServerHttpRequest)
14
*/
15
interface RequestItemParser<T> {
16
/** Extract the request path */
17
String getPath(T request);
18
19
/** Extract the remote address (client IP) */
20
String getRemoteAddress(T request);
21
22
/** Extract a specific header value */
23
String getHeader(T request, String key);
24
25
/** Extract a URL query parameter value */
26
String getUrlParam(T request, String paramName);
27
28
/** Extract a cookie value */
29
String getCookieValue(T request, String cookieName);
30
}
31
```
32
33
**Usage Examples:**
34
35
```java
36
// Example implementation for Spring WebFlux
37
public class WebFluxRequestItemParser implements RequestItemParser<ServerHttpRequest> {
38
@Override
39
public String getPath(ServerHttpRequest request) {
40
return request.getURI().getPath();
41
}
42
43
@Override
44
public String getRemoteAddress(ServerHttpRequest request) {
45
return request.getRemoteAddress() != null ?
46
request.getRemoteAddress().getAddress().getHostAddress() : null;
47
}
48
49
@Override
50
public String getHeader(ServerHttpRequest request, String key) {
51
return request.getHeaders().getFirst(key);
52
}
53
54
@Override
55
public String getUrlParam(ServerHttpRequest request, String paramName) {
56
return request.getQueryParams().getFirst(paramName);
57
}
58
59
@Override
60
public String getCookieValue(ServerHttpRequest request, String cookieName) {
61
HttpCookie cookie = request.getCookies().getFirst(cookieName);
62
return cookie != null ? cookie.getValue() : null;
63
}
64
}
65
66
// Example implementation for Servlet API
67
public class ServletRequestItemParser implements RequestItemParser<HttpServletRequest> {
68
@Override
69
public String getPath(HttpServletRequest request) {
70
return request.getRequestURI();
71
}
72
73
@Override
74
public String getRemoteAddress(HttpServletRequest request) {
75
return request.getRemoteAddr();
76
}
77
78
@Override
79
public String getHeader(HttpServletRequest request, String key) {
80
return request.getHeader(key);
81
}
82
83
@Override
84
public String getUrlParam(HttpServletRequest request, String paramName) {
85
return request.getParameter(paramName);
86
}
87
88
@Override
89
public String getCookieValue(HttpServletRequest request, String cookieName) {
90
Cookie[] cookies = request.getCookies();
91
if (cookies != null) {
92
for (Cookie cookie : cookies) {
93
if (cookieName.equals(cookie.getName())) {
94
return cookie.getValue();
95
}
96
}
97
}
98
return null;
99
}
100
}
101
```
102
103
### GatewayParamParser
104
105
Parser for extracting parameters from gateway requests based on gateway flow rules for parameter-based flow control.
106
107
```java { .api }
108
/**
109
* Parser for extracting parameters from gateway requests based on rules
110
* @param <T> Type of request object
111
*/
112
class GatewayParamParser<T> {
113
/** Constructor with request item parser */
114
GatewayParamParser(RequestItemParser<T> requestItemParser);
115
116
/**
117
* Parse parameters for a specific resource based on matching rules
118
* @param resource The resource name to parse parameters for
119
* @param request The gateway request object
120
* @param rulePredicate Predicate to filter applicable rules
121
* @return Array of parsed parameter values
122
*/
123
Object[] parseParameterFor(String resource, T request, Predicate<GatewayFlowRule> rulePredicate);
124
}
125
```
126
127
**Usage Examples:**
128
129
```java
130
// Create parser with request item parser
131
RequestItemParser<HttpServletRequest> itemParser = new ServletRequestItemParser();
132
GatewayParamParser<HttpServletRequest> paramParser = new GatewayParamParser<>(itemParser);
133
134
// Parse parameters for a specific resource
135
HttpServletRequest request = // ... get request
136
Object[] params = paramParser.parseParameterFor(
137
"user-api",
138
request,
139
rule -> rule.getParamItem() != null // Only rules with parameter items
140
);
141
142
// The returned array contains extracted parameter values based on the rules
143
// For example, if rules extract client IP and user ID header:
144
// params[0] might be "192.168.1.100" (client IP)
145
// params[1] might be "user123" (X-User-ID header value)
146
```
147
148
### ConfigurableRequestItemParser
149
150
Enhanced request item parser that allows custom extractors to be registered for specific request attributes.
151
152
```java { .api }
153
/**
154
* Configurable parser with custom extractors for request items
155
* @param <T> Type of request object
156
*/
157
class ConfigurableRequestItemParser<T> implements RequestItemParser<T> {
158
/** Constructor with delegate parser */
159
ConfigurableRequestItemParser(RequestItemParser<T> delegate);
160
161
// RequestItemParser interface methods
162
String getPath(T request);
163
String getRemoteAddress(T request);
164
String getHeader(T request, String key);
165
String getUrlParam(T request, String paramName);
166
String getCookieValue(T request, String cookieName);
167
168
// Extractor registration methods
169
/** Add custom path extractor (fluent interface) */
170
ConfigurableRequestItemParser<T> addPathExtractor(Function<T, String> extractor);
171
172
/** Add custom remote address extractor (fluent interface) */
173
ConfigurableRequestItemParser<T> addRemoteAddressExtractor(Function<T, String> extractor);
174
175
/** Add custom header extractor (fluent interface) */
176
ConfigurableRequestItemParser<T> addHeaderExtractor(BiFunction<T, String, String> extractor);
177
178
/** Add custom URL parameter extractor (fluent interface) */
179
ConfigurableRequestItemParser<T> addUrlParamExtractor(BiFunction<T, String, String> extractor);
180
181
/** Add custom cookie value extractor (fluent interface) */
182
ConfigurableRequestItemParser<T> addCookieValueExtractor(BiFunction<T, String, String> extractor);
183
}
184
```
185
186
**Usage Examples:**
187
188
```java
189
// Create configurable parser with base implementation
190
RequestItemParser<ServerHttpRequest> baseParser = new WebFluxRequestItemParser();
191
ConfigurableRequestItemParser<ServerHttpRequest> configurableParser =
192
new ConfigurableRequestItemParser<>(baseParser);
193
194
// Add custom extractors for special cases
195
configurableParser
196
.addRemoteAddressExtractor(request -> {
197
// Custom logic to extract real client IP from proxy headers
198
String xForwardedFor = request.getHeaders().getFirst("X-Forwarded-For");
199
if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
200
return xForwardedFor.split(",")[0].trim();
201
}
202
String xRealIp = request.getHeaders().getFirst("X-Real-IP");
203
if (xRealIp != null && !xRealIp.isEmpty()) {
204
return xRealIp;
205
}
206
// Fall back to default behavior
207
return baseParser.getRemoteAddress(request);
208
})
209
.addHeaderExtractor((request, key) -> {
210
// Custom header extraction with case-insensitive lookup
211
return request.getHeaders().entrySet().stream()
212
.filter(entry -> entry.getKey().equalsIgnoreCase(key))
213
.findFirst()
214
.map(entry -> entry.getValue().get(0))
215
.orElse(null);
216
});
217
218
// Use the configurable parser
219
GatewayParamParser<ServerHttpRequest> paramParser =
220
new GatewayParamParser<>(configurableParser);
221
```
222
223
### GatewayRegexCache
224
225
Cache for compiled regex patterns used in parameter matching to improve performance.
226
227
```java { .api }
228
/**
229
* Cache for compiled regex patterns used in gateway rules
230
*/
231
final class GatewayRegexCache {
232
/** Get compiled pattern from cache */
233
static Pattern getRegexPattern(String pattern);
234
235
/** Add pattern to cache, returns true if successfully compiled */
236
static boolean addRegexPattern(String pattern);
237
238
/** Clear all cached patterns */
239
static void clear();
240
}
241
```
242
243
**Usage Examples:**
244
245
```java
246
// Pre-compile and cache regex patterns
247
boolean added = GatewayRegexCache.addRegexPattern("user_\\d+");
248
249
// Retrieve compiled pattern (returns null if not found or invalid)
250
Pattern pattern = GatewayRegexCache.getRegexPattern("user_\\d+");
251
if (pattern != null) {
252
boolean matches = pattern.matcher("user_123").matches();
253
}
254
255
// Clear cache when patterns change
256
GatewayRegexCache.clear();
257
```
258
259
## Parameter Extraction Strategies
260
261
The parameter processing system supports five extraction strategies defined in `SentinelGatewayConstants`:
262
263
### Client IP (Strategy 0)
264
Extracts the client's IP address from the request.
265
266
```java
267
GatewayParamFlowItem ipParam = new GatewayParamFlowItem()
268
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP);
269
```
270
271
### Host (Strategy 1)
272
Extracts the Host header from the request.
273
274
```java
275
GatewayParamFlowItem hostParam = new GatewayParamFlowItem()
276
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HOST);
277
```
278
279
### Header (Strategy 2)
280
Extracts a specific header value (requires `fieldName`).
281
282
```java
283
GatewayParamFlowItem headerParam = new GatewayParamFlowItem()
284
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
285
.setFieldName("X-User-ID");
286
```
287
288
### URL Parameter (Strategy 3)
289
Extracts a specific URL query parameter (requires `fieldName`).
290
291
```java
292
GatewayParamFlowItem urlParam = new GatewayParamFlowItem()
293
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
294
.setFieldName("api_key");
295
```
296
297
### Cookie (Strategy 4)
298
Extracts a specific cookie value (requires `fieldName`).
299
300
```java
301
GatewayParamFlowItem cookieParam = new GatewayParamFlowItem()
302
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_COOKIE)
303
.setFieldName("session_id");
304
```
305
306
## Parameter Matching
307
308
Once parameters are extracted, they can be matched against patterns using different strategies:
309
310
### Exact Match (Strategy 0)
311
```java
312
paramItem.setPattern("premium_user")
313
.setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT);
314
```
315
316
### Prefix Match (Strategy 1)
317
```java
318
paramItem.setPattern("admin_")
319
.setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_PREFIX);
320
```
321
322
### Regex Match (Strategy 2)
323
```java
324
paramItem.setPattern("user_\\d+")
325
.setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX);
326
```
327
328
### Contains Match (Strategy 3)
329
```java
330
paramItem.setPattern("premium")
331
.setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS);
332
```
333
334
## Integration Example
335
336
Complete example showing parameter processing integration:
337
338
```java
339
// 1. Create request item parser for your gateway framework
340
RequestItemParser<HttpServletRequest> parser = new ServletRequestItemParser();
341
342
// 2. Create parameter parser
343
GatewayParamParser<HttpServletRequest> paramParser = new GatewayParamParser<>(parser);
344
345
// 3. Define parameter-based flow rule
346
GatewayParamFlowItem userParam = new GatewayParamFlowItem()
347
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
348
.setFieldName("X-User-Type")
349
.setPattern("premium")
350
.setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT);
351
352
GatewayFlowRule rule = new GatewayFlowRule("api-endpoint")
353
.setGrade(RuleConstant.FLOW_GRADE_QPS)
354
.setCount(1000) // Higher limit for premium users
355
.setParamItem(userParam);
356
357
// 4. Load rule
358
GatewayRuleManager.loadRules(Set.of(rule));
359
360
// 5. In request processing
361
HttpServletRequest request = // ... get request
362
Object[] params = paramParser.parseParameterFor("api-endpoint", request, r -> true);
363
// params[0] contains "premium" if X-User-Type header matches, null otherwise
364
```
365
366
## Best Practices
367
368
1. **Implement RequestItemParser appropriately** for your gateway framework
369
2. **Use ConfigurableRequestItemParser** for complex extraction logic
370
3. **Cache regex patterns** using GatewayRegexCache for better performance
371
4. **Handle null values** gracefully in parameter extraction
372
5. **Consider proxy headers** when extracting client IP addresses
373
6. **Use appropriate matching strategies** - exact for simple values, regex for complex patterns
374
7. **Pre-validate regex patterns** before using them in production
375
8. **Monitor parameter extraction performance** as it adds overhead to request processing