compliance/examples/rules/performance_rule_response_time.yaml
2025-05-16 15:18:02 +08:00

45 lines
1.3 KiB
YAML

id: response-time-threshold
name: 响应时间阈值规则
description: 验证API响应时间是否在允许的范围内
category: Performance
version: 1.0.0
severity: warning
is_enabled: true
tags:
- performance
- response-time
target_type: APIResponse
lifecycle: ResponseValidation
scope: ResponseTime
threshold: 500 # 毫秒
metric: response_time
unit: ms
code: |
def validate(context):
response = context.get('api_response')
if not response:
return {'is_valid': False, 'message': '缺少API响应对象'}
response_time = response.elapsed_time * 1000 # 转换为毫秒
threshold = context.get('threshold', 500) # 默认500毫秒
if response_time > threshold:
return {
'is_valid': False,
'message': f'响应时间 {response_time:.2f}ms 超过阈值 {threshold}ms',
'details': {
'actual_time': response_time,
'threshold': threshold,
'unit': 'ms'
}
}
return {
'is_valid': True,
'message': f'响应时间 {response_time:.2f}ms 在阈值 {threshold}ms 内',
'details': {
'actual_time': response_time,
'threshold': threshold,
'unit': 'ms'
}
}