Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1629ad21d6 | |||
| 3acd90ecc9 | |||
| d7fcbdde92 | |||
| 261f1d38e9 | |||
| 2d297eb996 | |||
| 8f1a8b6283 | |||
| faa9ffe2d9 | |||
| 5a86a4f950 | |||
| 668a0aca88 | |||
| 1c07acc01d | |||
| 7e6b2fc4dc | |||
| e393350c8b | |||
| 8173c2ff3f | |||
| 44d327139b | |||
| c392f7b47f | |||
| d3bc083b88 | |||
| 87fee6fe69 | |||
| c868e3befd | |||
| 0e9e6656db |
@@ -0,0 +1 @@
|
||||
upgrade-doc/v3/kafka/*.sh text eol=lf
|
||||
+1016
File diff suppressed because it is too large
Load Diff
+32
@@ -55,8 +55,33 @@ services:
|
||||
- SPRING_KAFKA_CONSUMER_AUTO_OFFSET_RESET=latest
|
||||
- SPRING_KAFKA_CONSUMER_ENABLE_AUTO_COMMIT=false
|
||||
- SPRING_KAFKA_CONSUMER_TOPIC=agent-01-syslog-topic
|
||||
- KAFKA_CONSUMER_LARGE_TOPIC=agent-01-syslog-topic.large
|
||||
# consumer-rule 是活跃原始日志消费节点,多实例通过同一消费组分担分区。
|
||||
- SYSLOG_RAW_CONSUMER_ENABLED=true
|
||||
# 特殊异常优先写入 DLT;DLT 失败也记录后放行,避免单条/单批异常永久阻塞分区。
|
||||
- SYSLOG_FAILURE_CONTINUITY_ENABLED=true
|
||||
- SYSLOG_FAILURE_CONTINUITY_DLT_PUBLISH_TIMEOUT_MS=1000
|
||||
# 积压采样默认开启;升级应用前先执行 upgrade-doc/v4/database 脚本。
|
||||
- SYSLOG_BACKLOG_SAMPLING_ENABLED=true
|
||||
- SYSLOG_BACKLOG_SAMPLING_START_LAG_MS=900000
|
||||
- SYSLOG_BACKLOG_SAMPLING_LAG_THRESHOLD_MS=3600000
|
||||
- SYSLOG_BACKLOG_SAMPLING_NORMAL_RETAIN_BPS=1000
|
||||
- SYSLOG_BACKLOG_SAMPLING_NON_NORMAL_RETAIN_BPS=2000
|
||||
- SYSLOG_BACKLOG_SAMPLING_DEGRADE_STEPS=10
|
||||
- SYSLOG_BACKLOG_SAMPLING_POLICY_VERSION=v2
|
||||
- SYSLOG_BACKLOG_SAMPLING_AUDIT_TIMEOUT_SECONDS=5
|
||||
- SYSLOG_BACKLOG_SAMPLING_AUDIT_RETRY_BACKOFF_MS=60000
|
||||
# 大日志的 poll、fetch、批次和规则计算线程池均独立且有界。
|
||||
- SYSLOG_LARGE_LISTENER_ENABLED=true
|
||||
- SYSLOG_LARGE_LISTENER_CONCURRENCY=1
|
||||
- SYSLOG_LARGE_LISTENER_MAX_POLL_RECORDS=5
|
||||
- SYSLOG_LARGE_LISTENER_MAX_PARTITION_FETCH_BYTES=33554432
|
||||
- SYSLOG_LARGE_LISTENER_FETCH_MAX_BYTES=67108864
|
||||
- SYSLOG_LARGE_PROCESSING_BATCH_MAX_BYTES=8388608
|
||||
- SYSLOG_LARGE_PROCESSOR_CORE_POOL_SIZE=1
|
||||
- SYSLOG_LARGE_PROCESSOR_MAX_POOL_SIZE=2
|
||||
- SYSLOG_LARGE_PROCESSOR_QUEUE_CAPACITY=10
|
||||
- KAFKA_RELIABILITY_MAX_REQUEST_SIZE=33554432
|
||||
# Retry/Replay 与 Raw 隔离,避免未到期重试占用实时消费线程。
|
||||
- SYSLOG_RELIABILITY_CONSUMER_GROUP_ID=agent-01-syslog-group-dm-retry
|
||||
- SYSLOG_RELIABILITY_CONSUMER_ENABLED=true
|
||||
@@ -79,6 +104,13 @@ services:
|
||||
- INFLUXDB_RAW_LEGACY_POINT_TIME_FALLBACK_ENABLED=true
|
||||
- INFLUXDB_RAW_QUERY_MAX_ROWS=10000
|
||||
- INFLUXDB_RAW_QUERY_MAX_RESPONSE_BYTES=10485760
|
||||
- INFLUXDB_RAW_MESSAGE_MAX_UTF8_BYTES=262144
|
||||
- INFLUXDB_RAW_WRITE_BATCH_MAX_BYTES=8388608
|
||||
# InfluxDB 原文写是非关键旁路:请求超时后熔断退避,主消费继续。
|
||||
- INFLUXDB_RAW_WRITE_REQUEST_TIMEOUT=5s
|
||||
- INFLUXDB_RAW_FAILURE_BACKOFF_MS=30000
|
||||
- DM_NORMAL_LARGE_FIELD_MAX_UTF8_BYTES=262144
|
||||
- DM_NON_NORMAL_LARGE_FIELD_MAX_UTF8_BYTES=262144
|
||||
- INFLUXDB_BATCH_SIZE=1000
|
||||
- INFLUXDB_FLUSH_INTERVAL=1000
|
||||
- INFLUXDB_CONNECTION_TIMEOUT=30s
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.Modules.NormalData;
|
||||
|
||||
/** 普通/非标采用较高保留率,倍率由当前策略自动计算;不改变实际采样或告警保留规则。 */
|
||||
@org.springframework.stereotype.Component
|
||||
public final class AdaptiveRawBatchSizer {
|
||||
private final int baseRecords;
|
||||
private final int maxRecords;
|
||||
|
||||
public AdaptiveRawBatchSizer(
|
||||
@org.springframework.beans.factory.annotation.Value("${syslog.raw-listener.max-poll-records:3000}") int baseRecords,
|
||||
@org.springframework.beans.factory.annotation.Value("${syslog.raw-listener.adaptive-max-records:5000}") int maxRecords) {
|
||||
if (baseRecords < 1 || maxRecords < baseRecords) {
|
||||
throw new IllegalArgumentException("普通自适应批量要求 1 <= 基础条数 <= 上限条数");
|
||||
}
|
||||
this.baseRecords = baseRecords;
|
||||
this.maxRecords = maxRecords;
|
||||
}
|
||||
|
||||
public int targetRecords(int normalRetainBps, int nonNormalRetainBps) {
|
||||
validateRate(normalRetainBps);
|
||||
validateRate(nonNormalRetainBps);
|
||||
int retainBps = Math.max(normalRetainBps, nonNormalRetainBps);
|
||||
if (retainBps == 0) return maxRecords;
|
||||
long numerator = (long) baseRecords * 10000L;
|
||||
long calculated = (numerator + retainBps - 1L) / retainBps;
|
||||
return (int) Math.min(maxRecords, calculated);
|
||||
}
|
||||
|
||||
public int getBaseRecords() { return baseRecords; }
|
||||
public int getMaxRecords() { return maxRecords; }
|
||||
|
||||
private static void validateRate(int rate) {
|
||||
if (rate < 0 || rate > 10000) throw new IllegalArgumentException("保留万分比必须在0~10000之间");
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.Modules.NormalData;
|
||||
|
||||
import com.config.BacklogSamplingProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
/** 按延迟阶梯计算当前保留率,再以 event_id 做确定性哈希采样。 */
|
||||
@Component
|
||||
public class BacklogSamplingDecider {
|
||||
private static final ZoneId RECEIVE_TIME_ZONE = ZoneId.of("Asia/Shanghai");
|
||||
private final BacklogSamplingProperties properties;
|
||||
|
||||
public BacklogSamplingDecider(BacklogSamplingProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public BacklogSamplingDecision decide(String eventId, LocalDateTime receivedAt,
|
||||
boolean hasAlarm, boolean hasNormal,
|
||||
boolean hasNonNormal) {
|
||||
return decide(eventId, receivedAt, hasAlarm, hasNormal, hasNonNormal, Instant.now());
|
||||
}
|
||||
|
||||
BacklogSamplingDecision decide(String eventId, LocalDateTime receivedAt,
|
||||
boolean hasAlarm, boolean hasNormal,
|
||||
boolean hasNonNormal, Instant now) {
|
||||
LocalDateTime effectiveReceivedAt = receivedAt == null
|
||||
? LocalDateTime.ofInstant(now, RECEIVE_TIME_ZONE) : receivedAt;
|
||||
long receivedEpochMs = effectiveReceivedAt.atZone(RECEIVE_TIME_ZONE).toInstant().toEpochMilli();
|
||||
long lagMs = Math.max(0L, now.toEpochMilli() - receivedEpochMs);
|
||||
LocalDateTime sourceHour = effectiveReceivedAt.truncatedTo(ChronoUnit.HOURS);
|
||||
int steps = Math.max(1, properties.getDegradeSteps());
|
||||
int currentStep = currentStep(
|
||||
lagMs, properties.getStartLagMs(), properties.getLagThresholdMs(), steps);
|
||||
int normalRetainBps = effectiveRetainBps(
|
||||
properties.getNormalRetainBps(), currentStep, steps);
|
||||
int nonNormalRetainBps = effectiveRetainBps(
|
||||
properties.getNonNormalRetainBps(), currentStep, steps);
|
||||
boolean degraded = properties.isEnabled() && currentStep > 0
|
||||
&& (normalRetainBps < BacklogSamplingProperties.BASIS_POINTS
|
||||
|| nonNormalRetainBps < BacklogSamplingProperties.BASIS_POINTS);
|
||||
if (!degraded) {
|
||||
return new BacklogSamplingDecision(false, true, true, true, lagMs, sourceHour,
|
||||
properties.getPolicyVersion(), BacklogSamplingProperties.BASIS_POINTS,
|
||||
BacklogSamplingProperties.BASIS_POINTS);
|
||||
}
|
||||
|
||||
// 没有产出行的 FILTERED 消息仍视为普通消息,使其 InfluxDB 原文遵守普通保留率。
|
||||
boolean normalCandidate = hasNormal || (!hasAlarm && !hasNonNormal);
|
||||
boolean keepNormal = !normalCandidate || sampled(eventId, "NORMAL",
|
||||
normalRetainBps, properties.getPolicyVersion());
|
||||
boolean keepNonNormal = !hasNonNormal || sampled(eventId, "NON_NORMAL",
|
||||
nonNormalRetainBps, properties.getPolicyVersion());
|
||||
boolean keepRaw = hasAlarm
|
||||
|| (normalCandidate && keepNormal)
|
||||
|| (hasNonNormal && keepNonNormal);
|
||||
return new BacklogSamplingDecision(true, keepNormal, keepNonNormal, keepRaw, lagMs,
|
||||
sourceHour, properties.getPolicyVersion(), normalRetainBps,
|
||||
nonNormalRetainBps);
|
||||
}
|
||||
|
||||
static int currentStep(long lagMs, long startLagMs, long thresholdMs, int steps) {
|
||||
if (lagMs <= startLagMs) return 0;
|
||||
if (lagMs >= thresholdMs) return steps;
|
||||
long degradableLagMs = lagMs - startLagMs;
|
||||
long degradableWindowMs = thresholdMs - startLagMs;
|
||||
return Math.min(steps, (int) Math.floor(
|
||||
((double) degradableLagMs / (double) degradableWindowMs) * steps));
|
||||
}
|
||||
|
||||
static int effectiveRetainBps(int minimumRetainBps, int currentStep, int steps) {
|
||||
if (currentStep <= 0) return BacklogSamplingProperties.BASIS_POINTS;
|
||||
if (currentStep >= steps) return minimumRetainBps;
|
||||
long totalDrop = BacklogSamplingProperties.BASIS_POINTS - minimumRetainBps;
|
||||
long appliedDrop = totalDrop * currentStep / steps;
|
||||
return (int) (BacklogSamplingProperties.BASIS_POINTS - appliedDrop);
|
||||
}
|
||||
|
||||
static boolean sampled(String eventId, String category, int retainBps, String policyVersion) {
|
||||
if (retainBps <= 0) return false;
|
||||
if (retainBps >= BacklogSamplingProperties.BASIS_POINTS) return true;
|
||||
String input = String.valueOf(policyVersion) + '\u0000' + category + '\u0000' + String.valueOf(eventId);
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest(input.getBytes(StandardCharsets.UTF_8));
|
||||
int value = ByteBuffer.wrap(digest, 0, 4).getInt() & Integer.MAX_VALUE;
|
||||
return value % BacklogSamplingProperties.BASIS_POINTS < retainBps;
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new IllegalStateException("JVM 缺少 SHA-256", impossible);
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.Modules.NormalData;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 一条原始 Kafka 消息完成规则计算后的稳定保留决策。 */
|
||||
public final class BacklogSamplingDecision {
|
||||
private final boolean degraded;
|
||||
private final boolean keepNormal;
|
||||
private final boolean keepNonNormal;
|
||||
private final boolean keepRaw;
|
||||
private final long lagMs;
|
||||
private final LocalDateTime sourceHour;
|
||||
private final String policyVersion;
|
||||
private final int normalRetainBps;
|
||||
private final int nonNormalRetainBps;
|
||||
|
||||
BacklogSamplingDecision(boolean degraded, boolean keepNormal, boolean keepNonNormal,
|
||||
boolean keepRaw, long lagMs, LocalDateTime sourceHour,
|
||||
String policyVersion, int normalRetainBps, int nonNormalRetainBps) {
|
||||
this.degraded = degraded;
|
||||
this.keepNormal = keepNormal;
|
||||
this.keepNonNormal = keepNonNormal;
|
||||
this.keepRaw = keepRaw;
|
||||
this.lagMs = lagMs;
|
||||
this.sourceHour = sourceHour;
|
||||
this.policyVersion = policyVersion;
|
||||
this.normalRetainBps = normalRetainBps;
|
||||
this.nonNormalRetainBps = nonNormalRetainBps;
|
||||
}
|
||||
|
||||
public boolean isDegraded() { return degraded; }
|
||||
public boolean isKeepNormal() { return keepNormal; }
|
||||
public boolean isKeepNonNormal() { return keepNonNormal; }
|
||||
public boolean isKeepRaw() { return keepRaw; }
|
||||
public long getLagMs() { return lagMs; }
|
||||
public LocalDateTime getSourceHour() { return sourceHour; }
|
||||
public String getPolicyVersion() { return policyVersion; }
|
||||
public int getNormalRetainBps() { return normalRetainBps; }
|
||||
public int getNonNormalRetainBps() { return nonNormalRetainBps; }
|
||||
}
|
||||
+43
-23
@@ -411,9 +411,6 @@ public class LogNormalProcessor {
|
||||
}
|
||||
if (ctx.dmNormalizeRuleList.size() > 1 && selectionConfig.isShadowEnabled()) {
|
||||
shadowSelect(ctx);
|
||||
if (ctx.invalidJson) {
|
||||
return invalidJsonResult(ctx, deviceID);
|
||||
}
|
||||
}
|
||||
if (optimizationProperties.getCompiledRule().isEnabled()) {
|
||||
return executeCompiled(ctx, deviceID);
|
||||
@@ -433,15 +430,15 @@ public class LogNormalProcessor {
|
||||
for (RuleSource source : ctx.dmNormalizeRuleList) {
|
||||
try {
|
||||
executeLegacyRule(ctx, deviceId, source);
|
||||
if (ctx.invalidJson) {
|
||||
return invalidJsonResult(ctx, deviceId);
|
||||
}
|
||||
} catch (Exception failure) {
|
||||
logger.error("泛化规则处理失败, eventId={}, ruleId={}",
|
||||
ctx.strSyslogUUID, source.getId(), failure);
|
||||
throw new IllegalStateException("标准化规则处理失败", failure);
|
||||
}
|
||||
}
|
||||
if (ctx.savedCount == 0 && ctx.filteredCount == 0 && ctx.invalidJson) {
|
||||
return invalidJsonResult(ctx, deviceId);
|
||||
}
|
||||
return finish(ctx);
|
||||
}
|
||||
|
||||
@@ -450,7 +447,7 @@ public class LogNormalProcessor {
|
||||
*/
|
||||
private NormalizationResult executeSelected(ProcessContext ctx, long deviceId) {
|
||||
List<RuleSelectionEngine.Candidate<ExecutionPlan>> candidates = collectCandidates(ctx);
|
||||
if (ctx.invalidJson) {
|
||||
if (candidates.isEmpty() && ctx.invalidJson) {
|
||||
return invalidJsonResult(ctx, deviceId);
|
||||
}
|
||||
RuleSelectionEngine.Decision<ExecutionPlan> decision =
|
||||
@@ -505,9 +502,9 @@ public class LogNormalProcessor {
|
||||
/** 关闭切换开关时仅做归属影子计算,不改变旧的多结果行为。 */
|
||||
private void shadowSelect(ProcessContext ctx) {
|
||||
try {
|
||||
List<RuleSelectionEngine.Candidate<ExecutionPlan>> candidates = collectCandidates(ctx);
|
||||
if (ctx.invalidJson) return;
|
||||
ruleSelectionEngine.select(candidates, ctx.strLogMsg, true);
|
||||
ProcessContext shadow = shadowContext(ctx);
|
||||
List<RuleSelectionEngine.Candidate<ExecutionPlan>> candidates = collectCandidates(shadow);
|
||||
ruleSelectionEngine.select(candidates, shadow.strLogMsg, true);
|
||||
} catch (Exception failure) {
|
||||
// 影子链路不能影响生产结果。
|
||||
logger.debug("规则归属影子计算失败: eventHash={}, error={}",
|
||||
@@ -525,14 +522,14 @@ public class LogNormalProcessor {
|
||||
if (compiledEnabled) {
|
||||
try {
|
||||
CompiledRule compiled = compiledRuleCache.get(source, ctx.executionMetrics);
|
||||
long parseStarted = System.nanoTime();
|
||||
if (!compiled.isApplicableTo(ctx.strLogMsg)) {
|
||||
continue;
|
||||
}
|
||||
ParsedMessage parsed = ctx.messageParseContext.parse(
|
||||
compiled, ctx.strLogMsg, ctx.executionMetrics);
|
||||
ctx.executionMetrics.addMessageParseNanos(System.nanoTime() - parseStarted);
|
||||
if (parsed == null) {
|
||||
if (isJsonRule(source)) {
|
||||
markInvalidJson(ctx, source);
|
||||
return candidates;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -559,6 +556,9 @@ public class LogNormalProcessor {
|
||||
}
|
||||
|
||||
private ExecutionPlan legacyCandidate(ProcessContext ctx, RuleSource source) {
|
||||
if (isJsonRule(source) && !isJsonRuleApplicable(source, ctx.strLogMsg)) {
|
||||
return null;
|
||||
}
|
||||
long parseStarted = System.nanoTime();
|
||||
globalMetrics.ruleJsonParse();
|
||||
LinkedHashMap<String, Object> parsed = getMessageToMap(
|
||||
@@ -680,9 +680,6 @@ public class LogNormalProcessor {
|
||||
// 首次失败原因由 CompiledRuleCache 按 fingerprint 限频记录;此处只回退该规则。
|
||||
try {
|
||||
executeLegacyRule(ctx, deviceId, source);
|
||||
if (ctx.invalidJson) {
|
||||
return invalidJsonResult(ctx, deviceId);
|
||||
}
|
||||
} catch (Exception legacyFailure) {
|
||||
logger.error("编译失败规则回退旧执行器后仍失败, eventId={}, ruleId={}",
|
||||
ctx.strSyslogUUID, source.getId(), legacyFailure);
|
||||
@@ -691,10 +688,13 @@ public class LogNormalProcessor {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
if (!rule.isApplicableTo(ctx.strLogMsg)) {
|
||||
continue;
|
||||
}
|
||||
ParsedMessage parsed = ctx.messageParseContext.parse(rule, ctx.strLogMsg, ctx.executionMetrics);
|
||||
if (parsed == null && isJsonRule(source)) {
|
||||
markInvalidJson(ctx, source);
|
||||
return invalidJsonResult(ctx, deviceId);
|
||||
continue;
|
||||
}
|
||||
if (parsed == null || parsed.getFields().isEmpty()) {
|
||||
rejectParsedMessage(ctx, deviceId, source);
|
||||
@@ -720,11 +720,17 @@ public class LogNormalProcessor {
|
||||
throw new IllegalStateException("编译标准化规则处理失败", failure);
|
||||
}
|
||||
}
|
||||
if (ctx.savedCount == 0 && ctx.filteredCount == 0 && ctx.invalidJson) {
|
||||
return invalidJsonResult(ctx, deviceId);
|
||||
}
|
||||
return finish(ctx);
|
||||
}
|
||||
|
||||
/** 执行单条旧格式规则,供旧主路径和编译不兼容规则的精确回退共同使用。 */
|
||||
private void executeLegacyRule(ProcessContext ctx, long deviceId, RuleSource source) {
|
||||
if (isJsonRule(source) && !isJsonRuleApplicable(source, ctx.strLogMsg)) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> rule = source.asLegacyMap();
|
||||
long parseStarted = System.nanoTime();
|
||||
globalMetrics.ruleJsonParse();
|
||||
@@ -775,14 +781,11 @@ public class LogNormalProcessor {
|
||||
ctx.rejectedCount++;
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 语法失败是当前消息可确定的业务终态:只产生一条非标记录,
|
||||
* 不再尝试后续规则,也不抛异常进入 Retry/DLT。
|
||||
*/
|
||||
/** 所有适用规则均未形成有效候选后,只产生一条 JSON 非标记录。 */
|
||||
private NormalizationResult invalidJsonResult(ProcessContext ctx, long deviceId) {
|
||||
RuleSource source = ctx.invalidJsonRule;
|
||||
ctx.syslogNonNormalMessage.setReason("JSON解析异常");
|
||||
ctx.syslogNonNormalMessage.setReasonDetail("发现非法JSON,已停止后续标准化规则处理, ruleId="
|
||||
ctx.syslogNonNormalMessage.setReasonDetail("所有适用JSON规则均解析失败,未形成可用候选, ruleId="
|
||||
+ (source == null ? "unknown" : source.getId()) + ", ruleName="
|
||||
+ (source == null ? "unknown" : source.getDisplayName()));
|
||||
if (!ctx.shadowMode) {
|
||||
@@ -805,6 +808,15 @@ public class LogNormalProcessor {
|
||||
return source != null && "json".equalsIgnoreCase(source.getDataType());
|
||||
}
|
||||
|
||||
private boolean isJsonRuleApplicable(RuleSource source, String message) {
|
||||
Cropper_paramsType cropper = getCropperParams(source.asLegacyMap());
|
||||
if (cropper == null || cropper.gethead_key() == null
|
||||
|| cropper.gethead_key().trim().isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
return message != null && message.contains(cropper.gethead_key());
|
||||
}
|
||||
|
||||
/** 现场坏 JSON 可能高频出现,WARN 每分钟最多一条,避免日志 I/O 反向拖慢消费。 */
|
||||
private void logInvalidJsonRateLimited(ProcessContext ctx, long deviceId, RuleSource source) {
|
||||
invalidJsonSinceLastWarn.incrementAndGet();
|
||||
@@ -815,7 +827,7 @@ public class LogNormalProcessor {
|
||||
return;
|
||||
}
|
||||
long count = invalidJsonSinceLastWarn.getAndSet(0L);
|
||||
logger.warn("JSON解析失败已直接转非标: countSinceLastLog={}, eventId={}, deviceId={}, "
|
||||
logger.warn("全部适用JSON候选解析失败已转非标: countSinceLastLog={}, eventId={}, deviceId={}, "
|
||||
+ "ruleId={}, messageLength={}",
|
||||
count, ctx.strSyslogUUID, deviceId,
|
||||
source == null ? null : source.getId(),
|
||||
@@ -1000,6 +1012,9 @@ public class LogNormalProcessor {
|
||||
Cropper_paramsType cropperParams = getCropperParams(dmNormalizeRule);
|
||||
if (dataType.equals("json")) {
|
||||
String strJson = logNormalData.ParserMessageJsonType(MsgContent, cropperParams);
|
||||
if (cropperParams != null && !hasCompleteJsonObjectBoundary(strJson)) {
|
||||
strJson = JsonParser.extractJsonFromLogMessage(strJson);
|
||||
}
|
||||
LinkedHashMap<String, Object> result1 = NestedJsonParserUtil.safeParseJson(strJson);
|
||||
if (result1 == null) return null;
|
||||
LinkedHashMap<String, Object> flattened = NestedJsonUtils.flattenNestedJson(result1);
|
||||
@@ -1030,6 +1045,11 @@ public class LogNormalProcessor {
|
||||
return linkMap;
|
||||
}
|
||||
|
||||
private static boolean hasCompleteJsonObjectBoundary(String value) {
|
||||
return value != null && value.length() >= 2
|
||||
&& value.charAt(0) == '{' && value.charAt(value.length() - 1) == '}';
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> getRuleList(long device_id) {
|
||||
List<Map<String, Object>> rulelst = dmNormalizeRuleService.selectByDeviceId((long) 1);
|
||||
if (rulelst == null) {
|
||||
|
||||
+973
-105
File diff suppressed because it is too large
Load Diff
+75
-12
@@ -30,9 +30,8 @@ import java.util.concurrent.TimeoutException;
|
||||
/**
|
||||
* Kafka 异常消息可靠路由器。
|
||||
*
|
||||
* <p>该组件把“业务处理失败”与“原 offset 是否允许推进”放在同一个同步边界内:
|
||||
* Retry/DLT 的 send Future 只有取得 Broker ACK 后才返回终态;发布失败或结果未知一律抛出,
|
||||
* 让原消息保持未提交。这样不会用一次异步方法调用冒充消息已经被补偿链路接管。</p>
|
||||
* <p>常规 Retry/DLT 的 send Future 只有取得 Broker ACK 后才返回终态;发布失败或结果未知会抛给
|
||||
* 调用方。活动 listener 外层另有连续性优先边界,可按现场策略记录后放行。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -53,8 +52,20 @@ public class SyslogFailureRouter {
|
||||
private String retry1hTopic;
|
||||
@Value("${syslog.reliability.dlt-topic:${spring.kafka.consumer.topic}.DLT}")
|
||||
private String dltTopic;
|
||||
@Value("${spring.kafka.consumer.large-topic:${spring.kafka.consumer.topic}.large}")
|
||||
private String largeOriginalTopic;
|
||||
@Value("${syslog.large-reliability.retry-1m-topic:${spring.kafka.consumer.large-topic}.RETRY.1M}")
|
||||
private String largeRetry1mTopic;
|
||||
@Value("${syslog.large-reliability.retry-10m-topic:${spring.kafka.consumer.large-topic}.RETRY.10M}")
|
||||
private String largeRetry10mTopic;
|
||||
@Value("${syslog.large-reliability.retry-1h-topic:${spring.kafka.consumer.large-topic}.RETRY.1H}")
|
||||
private String largeRetry1hTopic;
|
||||
@Value("${syslog.large-reliability.dlt-topic:${spring.kafka.consumer.large-topic}.DLT}")
|
||||
private String largeDltTopic;
|
||||
@Value("${syslog.reliability.publish-timeout-ms:30000}")
|
||||
private long publishTimeoutMs;
|
||||
@Value("${syslog.failure-continuity.dlt-publish-timeout-ms:1000}")
|
||||
private long continuityDltPublishTimeoutMs;
|
||||
@Value("${syslog.reliability.consumer-version:unknown}")
|
||||
private String consumerVersion;
|
||||
|
||||
@@ -122,14 +133,18 @@ public class SyslogFailureRouter {
|
||||
public TerminalState route(ConsumerRecord<String, String> record, MessageContext context, Throwable failure) {
|
||||
FailureCategory category = classify(failure);
|
||||
if (category == FailureCategory.SYSTEMIC) {
|
||||
// [SYSLOG-ALARM][KACK][已修复] 系统性依赖故障不倾倒 DLT,也不提交原 offset,由容器背压并等待恢复。
|
||||
// 常规路由把系统性故障上抛;活动 listener 的连续性边界再决定是否转 DLT 并放行。
|
||||
return TerminalState.PAUSED;
|
||||
}
|
||||
|
||||
int nextAttempt = Math.max(0, context.getAttemptCount()) + 1;
|
||||
boolean permanent = category == FailureCategory.PERMANENT_DATA;
|
||||
boolean exhausted = nextAttempt > 3;
|
||||
String targetTopic = (permanent || exhausted) ? dltTopic : retryTopic(nextAttempt);
|
||||
boolean largeLane = largeOriginalTopic != null
|
||||
&& largeOriginalTopic.equals(context.getOriginalTopic());
|
||||
String targetTopic = (permanent || exhausted)
|
||||
? (largeLane ? largeDltTopic : dltTopic)
|
||||
: retryTopic(nextAttempt, largeLane);
|
||||
Instant nextRetryAt = (permanent || exhausted) ? null : Instant.now().plusSeconds(delaySeconds(nextAttempt));
|
||||
|
||||
FailureEnvelope source = readEnvelope(record.value());
|
||||
@@ -165,11 +180,59 @@ public class SyslogFailureRouter {
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* 连续性优先兜底:把无法安全完成当前处理阶段的原消息直接写入 DLT。
|
||||
* 本方法仍显式报告发布失败;是否继续提交原 offset 由调用方的连续性策略决定。
|
||||
*/
|
||||
public TerminalState routeContinuityDlt(ConsumerRecord<String, String> record,
|
||||
MessageContext context,
|
||||
Throwable failure,
|
||||
String failedStage) {
|
||||
int nextAttempt = Math.max(0, context.getAttemptCount()) + 1;
|
||||
boolean largeLane = largeOriginalTopic != null
|
||||
&& largeOriginalTopic.equals(context.getOriginalTopic());
|
||||
String targetTopic = largeLane ? largeDltTopic : dltTopic;
|
||||
FailureEnvelope source = readEnvelope(record.value());
|
||||
FailureEnvelope envelope = new FailureEnvelope();
|
||||
envelope.setEnvelopeType(ENVELOPE_TYPE);
|
||||
envelope.setEventId(context.getEventId());
|
||||
envelope.setDeviceId(context.getDeviceId() != null ? context.getDeviceId()
|
||||
: (source == null ? null : source.getDeviceId()));
|
||||
envelope.setOriginalTopic(source == null ? record.topic() : source.getOriginalTopic());
|
||||
envelope.setOriginalPartition(source == null ? record.partition() : source.getOriginalPartition());
|
||||
envelope.setOriginalOffset(source == null ? record.offset() : source.getOriginalOffset());
|
||||
envelope.setCurrentTopic(record.topic());
|
||||
envelope.setFirstReceivedAt(context.getFirstReceivedAt());
|
||||
envelope.setFailedStage(failedStage == null ? "UNKNOWN" : failedStage);
|
||||
envelope.setErrorCode("SYSLOG_CONTINUITY_BYPASS");
|
||||
Throwable root = rootCause(failure);
|
||||
envelope.setErrorType(root.getClass().getName());
|
||||
envelope.setErrorMessage(sanitize(root.getMessage()));
|
||||
envelope.setAttemptCount(nextAttempt);
|
||||
envelope.setNextRetryAt(null);
|
||||
envelope.setRuleId(source == null ? null : source.getRuleId());
|
||||
envelope.setRuleVersion(source == null ? null : source.getRuleVersion());
|
||||
envelope.setConsumerVersion(consumerVersion);
|
||||
envelope.setOriginalPayload(context.getPayload());
|
||||
envelope.setPointTimeNs(context.getPointTimeNs());
|
||||
|
||||
publishAndAwait(targetTopic, context.getEventId(), envelope,
|
||||
Math.max(1L, continuityDltPublishTimeoutMs));
|
||||
log.debug("[SYSLOG_CONTINUITY] 特殊异常已可靠写入 DLT: eventId={}, "
|
||||
+ "stage={}, target={}, errorType={}",
|
||||
context.getEventId(), envelope.getFailedStage(), targetTopic, envelope.getErrorType());
|
||||
return TerminalState.DLT_PUBLISHED;
|
||||
}
|
||||
|
||||
private void publishAndAwait(String topic, String key, FailureEnvelope envelope) {
|
||||
publishAndAwait(topic, key, envelope, publishTimeoutMs);
|
||||
}
|
||||
|
||||
private void publishAndAwait(String topic, String key, FailureEnvelope envelope, long timeoutMs) {
|
||||
try {
|
||||
String body = objectMapper.writeValueAsString(envelope);
|
||||
// [流程节点4.3] 必须等待 Broker ACK;仅调用 send() 不构成 RETRY_PUBLISHED/DLT_PUBLISHED。
|
||||
kafkaTemplate.send(topic, key, body).get(publishTimeoutMs, TimeUnit.MILLISECONDS);
|
||||
kafkaTemplate.send(topic, key, body).get(timeoutMs, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new FailurePublishException("发布异常消息时线程被中断,原 offset 不得提交", interrupted);
|
||||
@@ -191,8 +254,8 @@ public class SyslogFailureRouter {
|
||||
return FailureCategory.TRANSIENT;
|
||||
}
|
||||
Throwable root = rootCause(failure);
|
||||
// InfluxDB 400 数据格式错误只影响当前消息,可直接隔离;
|
||||
// 连接、超时、5xx 等 InfluxDB 故障属于系统性依赖故障,必须保留原 offset,避免 DLT 风暴。
|
||||
// InfluxDB 400 数据格式错误只影响当前消息,可直接隔离;连接、超时、5xx 属于系统性依赖故障。
|
||||
// 活动原文批写链路会在外层非阻塞旁路边界覆盖其 offset 行为,不能因此阻塞主消费。
|
||||
if (root instanceof BadRequestException) {
|
||||
return FailureCategory.PERMANENT_DATA;
|
||||
}
|
||||
@@ -256,10 +319,10 @@ public class SyslogFailureRouter {
|
||||
return record.timestamp() > 0 ? Instant.ofEpochMilli(record.timestamp()) : Instant.now();
|
||||
}
|
||||
|
||||
private String retryTopic(int attempt) {
|
||||
if (attempt == 1) return retry1mTopic;
|
||||
if (attempt == 2) return retry10mTopic;
|
||||
return retry1hTopic;
|
||||
private String retryTopic(int attempt, boolean largeLane) {
|
||||
if (attempt == 1) return largeLane ? largeRetry1mTopic : retry1mTopic;
|
||||
if (attempt == 2) return largeLane ? largeRetry10mTopic : retry10mTopic;
|
||||
return largeLane ? largeRetry1hTopic : retry1hTopic;
|
||||
}
|
||||
|
||||
private long delaySeconds(int attempt) {
|
||||
|
||||
+22
@@ -63,8 +63,30 @@ public class NormalizationCacheInvalidationService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空规则专属 Spring Cache,并按设备精确广播 JetCache BOTH 失效。
|
||||
*
|
||||
* <p>JetCache 没有安全的全库 clear;调用方传入数据库中的全部设备 ID,既能删除共享 L2,
|
||||
* 又能通过 syncLocal 让其他实例立即移除对应 L1,且不会误删同 Redis 中的其他业务数据。</p>
|
||||
*/
|
||||
public void invalidateAllRules(Collection<Long> deviceIds) {
|
||||
clearSpring("normalizeRule");
|
||||
metrics.invalidation("local");
|
||||
if (deviceIds == null) return;
|
||||
for (Long deviceId : deviceIds) {
|
||||
if (deviceId == null) continue;
|
||||
jetCacheInvalidator.rulesForDevice(deviceId);
|
||||
metrics.invalidation("remote");
|
||||
}
|
||||
}
|
||||
|
||||
private void evictSpring(String cacheName, Object key) {
|
||||
Cache cache = springCacheManager.getCache(cacheName);
|
||||
if (cache != null) cache.evict(key);
|
||||
}
|
||||
|
||||
private void clearSpring(String cacheName) {
|
||||
Cache cache = springCacheManager.getCache(cacheName);
|
||||
if (cache != null) cache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.Modules.NormalData.compiled.CompiledRuleCache;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.redis.connection.Message;
|
||||
import org.springframework.data.redis.connection.MessageListener;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
/** 通过 Redis Pub/Sub 让所有消费节点同步清理 JVM 本地编译规则缓存。 */
|
||||
@Component
|
||||
public class NormalizationCompiledCacheInvalidationBus implements MessageListener {
|
||||
public static final String TOPIC = "xdr:norm:v1:compiled-rule:invalidate";
|
||||
private static final String ALL = "ALL";
|
||||
private static final String RULES_PREFIX = "RULES:";
|
||||
private static final Logger log = LoggerFactory.getLogger(
|
||||
NormalizationCompiledCacheInvalidationBus.class);
|
||||
|
||||
private final CompiledRuleCache compiledRuleCache;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
|
||||
public NormalizationCompiledCacheInvalidationBus(CompiledRuleCache compiledRuleCache,
|
||||
StringRedisTemplate redisTemplate) {
|
||||
this.compiledRuleCache = compiledRuleCache;
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
public void invalidateRulesEverywhere(Collection<Long> ruleIds) {
|
||||
Set<Long> distinct = positiveIds(ruleIds);
|
||||
if (distinct.isEmpty()) return;
|
||||
for (Long ruleId : distinct) compiledRuleCache.invalidateRule(ruleId);
|
||||
redisTemplate.convertAndSend(TOPIC, ruleMessage(distinct));
|
||||
}
|
||||
|
||||
public void invalidateAllEverywhere() {
|
||||
compiledRuleCache.invalidateAll();
|
||||
redisTemplate.convertAndSend(TOPIC, ALL);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(Message message, byte[] pattern) {
|
||||
if (message == null || message.getBody() == null) return;
|
||||
String command = new String(message.getBody(), StandardCharsets.UTF_8).trim();
|
||||
if (ALL.equals(command)) {
|
||||
compiledRuleCache.invalidateAll();
|
||||
return;
|
||||
}
|
||||
if (!command.startsWith(RULES_PREFIX)) {
|
||||
log.warn("忽略未知的规则缓存失效广播: {}", command);
|
||||
return;
|
||||
}
|
||||
String ids = command.substring(RULES_PREFIX.length());
|
||||
if (ids.isEmpty()) return;
|
||||
for (String value : ids.split(",")) {
|
||||
try {
|
||||
long ruleId = Long.parseLong(value);
|
||||
if (ruleId > 0L) compiledRuleCache.invalidateRule(ruleId);
|
||||
} catch (NumberFormatException invalidId) {
|
||||
log.warn("忽略非法的规则缓存失效广播参数: {}", value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<Long> positiveIds(Collection<Long> ruleIds) {
|
||||
Set<Long> distinct = new LinkedHashSet<>();
|
||||
if (ruleIds == null) return distinct;
|
||||
for (Long ruleId : ruleIds) {
|
||||
if (ruleId != null && ruleId > 0L) distinct.add(ruleId);
|
||||
}
|
||||
return distinct;
|
||||
}
|
||||
|
||||
private static String ruleMessage(Collection<Long> ruleIds) {
|
||||
StringJoiner values = new StringJoiner(",", RULES_PREFIX, "");
|
||||
for (Long ruleId : ruleIds) values.add(ruleId.toString());
|
||||
return values.toString();
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.common.mapper.DeviceDeviceMapper;
|
||||
import com.common.mapper.DmNormalizeRuleMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/** 管理接口使用的规则缓存清理编排;不会清除设备、任务或其他业务 Redis 数据。 */
|
||||
@Service
|
||||
public class NormalizationRuleCacheManagementService {
|
||||
private final NormalizationCacheInvalidationService invalidationService;
|
||||
private final NormalizationCompiledCacheInvalidationBus compiledCacheInvalidationBus;
|
||||
private final DeviceDeviceMapper deviceMapper;
|
||||
private final DmNormalizeRuleMapper ruleMapper;
|
||||
|
||||
public NormalizationRuleCacheManagementService(
|
||||
NormalizationCacheInvalidationService invalidationService,
|
||||
NormalizationCompiledCacheInvalidationBus compiledCacheInvalidationBus,
|
||||
DeviceDeviceMapper deviceMapper,
|
||||
DmNormalizeRuleMapper ruleMapper) {
|
||||
this.invalidationService = invalidationService;
|
||||
this.compiledCacheInvalidationBus = compiledCacheInvalidationBus;
|
||||
this.deviceMapper = deviceMapper;
|
||||
this.ruleMapper = ruleMapper;
|
||||
}
|
||||
|
||||
/** 清理一个设备的规则快照,并移除该设备当前关联规则的实体和编译缓存。 */
|
||||
public ClearResult clearDevice(long deviceId) {
|
||||
if (deviceId <= 0L) throw new IllegalArgumentException("deviceId 必须大于 0");
|
||||
Set<Long> ruleIds = new LinkedHashSet<>();
|
||||
addAllNonNull(ruleIds, nullSafe(ruleMapper.selectRuleIdsByDeviceId(deviceId)));
|
||||
invalidationService.invalidateRulesForDevice(deviceId);
|
||||
for (Long ruleId : ruleIds) {
|
||||
invalidationService.invalidateRuleEntity(ruleId);
|
||||
}
|
||||
compiledCacheInvalidationBus.invalidateRulesEverywhere(ruleIds);
|
||||
return new ClearResult("DEVICE", deviceId, 1, ruleIds.size());
|
||||
}
|
||||
|
||||
/** 清理所有设备规则快照、规则实体和当前 JVM 的全部编译缓存。 */
|
||||
public ClearResult clearAll() {
|
||||
Set<Long> deviceIds = new LinkedHashSet<>();
|
||||
addAllNonNull(deviceIds, deviceMapper.selectAllIds());
|
||||
// 即使存在历史孤立关联,也应删除其规则快照键。
|
||||
addAllNonNull(deviceIds, ruleMapper.selectAllAssociatedDeviceIds());
|
||||
invalidationService.invalidateAllRules(deviceIds);
|
||||
compiledCacheInvalidationBus.invalidateAllEverywhere();
|
||||
return new ClearResult("ALL", null, deviceIds.size(), 0);
|
||||
}
|
||||
|
||||
private static List<Long> nullSafe(List<Long> values) {
|
||||
return values == null ? Collections.emptyList() : values;
|
||||
}
|
||||
|
||||
private static void addAllNonNull(Set<Long> target, Collection<Long> values) {
|
||||
if (values == null) return;
|
||||
for (Long value : values) if (value != null) target.add(value);
|
||||
}
|
||||
|
||||
public static final class ClearResult {
|
||||
private final String scope;
|
||||
private final Long deviceId;
|
||||
private final int deviceCount;
|
||||
private final int associatedRuleCount;
|
||||
|
||||
public ClearResult(String scope, Long deviceId, int deviceCount, int associatedRuleCount) {
|
||||
this.scope = scope;
|
||||
this.deviceId = deviceId;
|
||||
this.deviceCount = deviceCount;
|
||||
this.associatedRuleCount = associatedRuleCount;
|
||||
}
|
||||
|
||||
public String getScope() { return scope; }
|
||||
public Long getDeviceId() { return deviceId; }
|
||||
public int getDeviceCount() { return deviceCount; }
|
||||
public int getAssociatedRuleCount() { return associatedRuleCount; }
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -1,6 +1,5 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.Modules.NormalData.compiled.CompiledRuleCache;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -14,21 +13,21 @@ public class NormalizeRuleCacheInvalidationListener {
|
||||
private static final Logger log = LoggerFactory.getLogger(NormalizeRuleCacheInvalidationListener.class);
|
||||
|
||||
private final NormalizationCacheInvalidationService invalidationService;
|
||||
private final CompiledRuleCache compiledRuleCache;
|
||||
private final NormalizationCompiledCacheInvalidationBus compiledCacheInvalidationBus;
|
||||
private final NormalizationRuleMetrics metrics;
|
||||
|
||||
public NormalizeRuleCacheInvalidationListener(NormalizationCacheInvalidationService invalidationService,
|
||||
CompiledRuleCache compiledRuleCache,
|
||||
NormalizationCompiledCacheInvalidationBus compiledCacheInvalidationBus,
|
||||
NormalizationRuleMetrics metrics) {
|
||||
this.invalidationService = invalidationService;
|
||||
this.compiledRuleCache = compiledRuleCache;
|
||||
this.compiledCacheInvalidationBus = compiledCacheInvalidationBus;
|
||||
this.metrics = metrics;
|
||||
}
|
||||
|
||||
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
|
||||
public void afterCommit(NormalizeRuleChangedEvent event) {
|
||||
metrics.invalidation("after_commit");
|
||||
// 先移除跨 JVM 的规则事实,再清除本 JVM 所有历史 fingerprint 编译对象。
|
||||
// 先移除跨 JVM 的规则事实,再广播清除所有 JVM 的历史 fingerprint 对象。
|
||||
for (Long deviceId : event.getDeviceIds()) {
|
||||
try {
|
||||
invalidationService.invalidateRulesForDevice(deviceId);
|
||||
@@ -39,7 +38,8 @@ public class NormalizeRuleCacheInvalidationListener {
|
||||
}
|
||||
}
|
||||
try {
|
||||
compiledRuleCache.invalidateRule(event.getRuleId());
|
||||
compiledCacheInvalidationBus.invalidateRulesEverywhere(
|
||||
java.util.Collections.singleton(event.getRuleId()));
|
||||
} catch (RuntimeException cacheFailure) {
|
||||
metrics.invalidation("failure");
|
||||
// 数据库事实已提交;raw rules 的短 TTL 是最终一致性兜底。
|
||||
|
||||
+27
@@ -1,6 +1,7 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import com.Modules.NormalData.logNormalData;
|
||||
import com.common.util.JsonParser;
|
||||
import com.common.util.NestedJsonParserUtil;
|
||||
import com.common.util.NestedJsonUtils;
|
||||
|
||||
@@ -85,6 +86,16 @@ public final class CompiledRule {
|
||||
LinkedHashMap<String, Object> parsed;
|
||||
switch (dataType) {
|
||||
case "json":
|
||||
// 历史 JSON 规则的空 tail cropper 使用“head 起点 + offset”语义,部分规则
|
||||
// 因而会保留诸如 "7|!alarm|!" 的前缀。只在 JSON 专用路径重新收敛到
|
||||
// 完整对象边界,避免改变 KV/SEP/REGEX 及既有 offset 的全局兼容语义。
|
||||
if (cropper != null && !hasCompleteObjectBoundary(cropped)) {
|
||||
try {
|
||||
cropped = JsonParser.extractJsonFromLogMessage(cropped);
|
||||
} catch (IllegalArgumentException incompleteJson) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
LinkedHashMap<String, Object> nested = NestedJsonParserUtil.safeParseJson(cropped);
|
||||
parsed = nested == null ? null : NestedJsonUtils.flattenNestedJson(nested);
|
||||
break;
|
||||
@@ -106,6 +117,22 @@ public final class CompiledRule {
|
||||
return parsed == null ? null : new ParsedMessage(parsed);
|
||||
}
|
||||
|
||||
/**
|
||||
* cropper 的 head_key 是规则格式指纹。消息中不存在该指纹时表示规则不适用,
|
||||
* 不能把空截取结果误判为原始消息 JSON 非法。
|
||||
*/
|
||||
public boolean isApplicableTo(String message) {
|
||||
if (!"json".equals(dataType) || cropper == null || empty(cropper.getHeadKey())) {
|
||||
return true;
|
||||
}
|
||||
return message != null && message.contains(cropper.getHeadKey());
|
||||
}
|
||||
|
||||
private static boolean hasCompleteObjectBoundary(String value) {
|
||||
return value != null && value.length() >= 2
|
||||
&& value.charAt(0) == '{' && value.charAt(value.length() - 1) == '}';
|
||||
}
|
||||
|
||||
public Map<String, Object> map(ParsedMessage message) {
|
||||
Map<String, Object> destination = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Object> source : message.getFields().entrySet()) {
|
||||
|
||||
+12
@@ -192,6 +192,18 @@ public class CompiledRuleCache {
|
||||
metrics.compiledCacheGauge(compiled.estimatedSize(), evictions.sum());
|
||||
}
|
||||
|
||||
/** 清空当前 JVM 中所有规则编译结果、匹配画像及短失败缓存。 */
|
||||
public void invalidateAll() {
|
||||
compiled.invalidateAll();
|
||||
matchProfiles.invalidateAll();
|
||||
failures.invalidateAll();
|
||||
matchFailures.invalidateAll();
|
||||
loggedFailures.invalidateAll();
|
||||
keysByRule.invalidateAll();
|
||||
matchKeysByRule.invalidateAll();
|
||||
metrics.compiledCacheGauge(0L, evictions.sum());
|
||||
}
|
||||
|
||||
public long estimatedSize() { return compiled.estimatedSize(); }
|
||||
public long compileSuccessCount() { return compileSuccess.sum(); }
|
||||
public long compileFailureCount() { return compileFailure.sum(); }
|
||||
|
||||
+6
-5
@@ -170,10 +170,10 @@ public class CompiledRuleCompiler {
|
||||
}
|
||||
|
||||
private List<CompiledFilterGroup> compileFilters(JsonNode node, RuleSource source) {
|
||||
node = decodeEmbeddedJson(node, source, "filters_params");
|
||||
if (node == null || node.isNull()) return Collections.emptyList();
|
||||
// 旧执行器遇到 []、空字符串等非对象结构时捕获异常并按“无过滤条件”继续。
|
||||
// 字符串即使内容是 JSON 对象也不会被旧执行器二次解析,必须同样忽略。
|
||||
// 编译路径必须保持相同语义,不能让历史脏格式阻塞整条消息。
|
||||
// Fastjson 的 JSONObject.getJSONObject 会二次解析合法的内嵌 JSON 字符串,
|
||||
// 因此编译路径也必须支持该历史存储格式。其余非对象结构仍按旧执行器语义忽略。
|
||||
if (!node.isObject()) return Collections.emptyList();
|
||||
JsonNode groups = node.get("expressions");
|
||||
if (groups == null || groups.isNull()) return Collections.emptyList();
|
||||
@@ -191,9 +191,10 @@ public class CompiledRuleCompiler {
|
||||
}
|
||||
|
||||
private List<CompiledCompletion> compileCompletions(JsonNode node, RuleSource source) {
|
||||
node = decodeEmbeddedJson(node, source, "complete_columns");
|
||||
if (node == null || node.isNull()) return Collections.emptyList();
|
||||
// 旧补全服务对 {}、空字符串等非数组结构捕获异常后按“无补全配置”继续。
|
||||
// 字符串即使内容是 JSON 数组也不会被旧执行器二次解析,必须同样忽略。
|
||||
// Fastjson 的 JSONObject.getJSONArray 会二次解析合法的内嵌 JSON 字符串,
|
||||
// 现场规则普遍沿用这种格式;其余非数组结构仍按旧执行器语义忽略。
|
||||
if (!node.isArray()) return Collections.emptyList();
|
||||
List<CompiledCompletion> result = new ArrayList<>();
|
||||
for (JsonNode completion : node) {
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.common.mapper;
|
||||
|
||||
import com.common.service.BacklogRetentionDelta;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface BacklogRetentionAuditMapper {
|
||||
int upsert(BacklogRetentionDelta delta);
|
||||
}
|
||||
+4
-1
@@ -21,6 +21,9 @@ public interface DeviceDeviceMapper {
|
||||
*/
|
||||
List<DeviceDevice> selectAll();
|
||||
|
||||
/** 规则缓存全量失效只需要主键,避免加载整行设备信息。 */
|
||||
List<Long> selectAllIds();
|
||||
|
||||
/**
|
||||
* 根据IP地址查询设备
|
||||
*/
|
||||
@@ -90,4 +93,4 @@ public interface DeviceDeviceMapper {
|
||||
* 根据厂商查询设备
|
||||
*/
|
||||
List<DeviceDevice> selectByVendor(String vendor);
|
||||
}
|
||||
}
|
||||
|
||||
+4
@@ -24,6 +24,10 @@ public interface DmNormalizeRuleMapper {
|
||||
|
||||
List<Long> selectDeviceIdsByRuleId(@Param("ruleId") Long ruleId);
|
||||
|
||||
List<Long> selectRuleIdsByDeviceId(@Param("deviceId") Long deviceId);
|
||||
|
||||
List<Long> selectAllAssociatedDeviceIds();
|
||||
|
||||
/**
|
||||
* 根据ID更新数据标准化规则
|
||||
* @param rule 数据标准化规则对象
|
||||
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package com.common.service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Objects;
|
||||
|
||||
/** 一批积压消息按来源小时、Topic、Partition 聚合后的采样审计增量。 */
|
||||
public final class BacklogRetentionDelta {
|
||||
private final LocalDateTime sourceHour;
|
||||
private final String sourceTopic;
|
||||
private final int kafkaPartition;
|
||||
private final String policyVersion;
|
||||
private final int normalRetainBps;
|
||||
private final int nonNormalRetainBps;
|
||||
private long messageTotal;
|
||||
private long alarmRowsTotal;
|
||||
private long alarmRowsSaved;
|
||||
private long normalRowsTotal;
|
||||
private long normalRowsSaved;
|
||||
private long normalRowsDropped;
|
||||
private long nonNormalRowsTotal;
|
||||
private long nonNormalRowsSaved;
|
||||
private long nonNormalRowsDropped;
|
||||
private long rawTotal;
|
||||
private long rawSaved;
|
||||
private long rawDropped;
|
||||
private long minLagMs;
|
||||
private long maxLagMs;
|
||||
|
||||
public BacklogRetentionDelta(LocalDateTime sourceHour, String sourceTopic, int kafkaPartition,
|
||||
String policyVersion, int normalRetainBps, int nonNormalRetainBps,
|
||||
long messageTotal, long alarmRowsTotal, long alarmRowsSaved,
|
||||
long normalRowsTotal, long normalRowsSaved, long normalRowsDropped,
|
||||
long nonNormalRowsTotal, long nonNormalRowsSaved,
|
||||
long nonNormalRowsDropped, long rawTotal, long rawSaved,
|
||||
long rawDropped, long minLagMs, long maxLagMs) {
|
||||
this.sourceHour = Objects.requireNonNull(sourceHour, "sourceHour");
|
||||
this.sourceTopic = Objects.requireNonNull(sourceTopic, "sourceTopic");
|
||||
this.kafkaPartition = kafkaPartition;
|
||||
this.policyVersion = Objects.requireNonNull(policyVersion, "policyVersion");
|
||||
this.normalRetainBps = normalRetainBps;
|
||||
this.nonNormalRetainBps = nonNormalRetainBps;
|
||||
this.messageTotal = messageTotal;
|
||||
this.alarmRowsTotal = alarmRowsTotal;
|
||||
this.alarmRowsSaved = alarmRowsSaved;
|
||||
this.normalRowsTotal = normalRowsTotal;
|
||||
this.normalRowsSaved = normalRowsSaved;
|
||||
this.normalRowsDropped = normalRowsDropped;
|
||||
this.nonNormalRowsTotal = nonNormalRowsTotal;
|
||||
this.nonNormalRowsSaved = nonNormalRowsSaved;
|
||||
this.nonNormalRowsDropped = nonNormalRowsDropped;
|
||||
this.rawTotal = rawTotal;
|
||||
this.rawSaved = rawSaved;
|
||||
this.rawDropped = rawDropped;
|
||||
this.minLagMs = minLagMs;
|
||||
this.maxLagMs = maxLagMs;
|
||||
}
|
||||
|
||||
public void merge(BacklogRetentionDelta other) {
|
||||
if (!sameKey(other)) throw new IllegalArgumentException("不能合并不同维度的采样审计增量");
|
||||
messageTotal += other.messageTotal;
|
||||
alarmRowsTotal += other.alarmRowsTotal;
|
||||
alarmRowsSaved += other.alarmRowsSaved;
|
||||
normalRowsTotal += other.normalRowsTotal;
|
||||
normalRowsSaved += other.normalRowsSaved;
|
||||
normalRowsDropped += other.normalRowsDropped;
|
||||
nonNormalRowsTotal += other.nonNormalRowsTotal;
|
||||
nonNormalRowsSaved += other.nonNormalRowsSaved;
|
||||
nonNormalRowsDropped += other.nonNormalRowsDropped;
|
||||
rawTotal += other.rawTotal;
|
||||
rawSaved += other.rawSaved;
|
||||
rawDropped += other.rawDropped;
|
||||
minLagMs = Math.min(minLagMs, other.minLagMs);
|
||||
maxLagMs = Math.max(maxLagMs, other.maxLagMs);
|
||||
}
|
||||
|
||||
public BacklogRetentionDelta copy() {
|
||||
return new BacklogRetentionDelta(sourceHour, sourceTopic, kafkaPartition, policyVersion,
|
||||
normalRetainBps, nonNormalRetainBps, messageTotal, alarmRowsTotal,
|
||||
alarmRowsSaved, normalRowsTotal, normalRowsSaved, normalRowsDropped,
|
||||
nonNormalRowsTotal, nonNormalRowsSaved, nonNormalRowsDropped,
|
||||
rawTotal, rawSaved, rawDropped, minLagMs, maxLagMs);
|
||||
}
|
||||
|
||||
private boolean sameKey(BacklogRetentionDelta other) {
|
||||
return other != null && kafkaPartition == other.kafkaPartition
|
||||
&& normalRetainBps == other.normalRetainBps
|
||||
&& nonNormalRetainBps == other.nonNormalRetainBps
|
||||
&& sourceHour.equals(other.sourceHour)
|
||||
&& sourceTopic.equals(other.sourceTopic)
|
||||
&& policyVersion.equals(other.policyVersion);
|
||||
}
|
||||
|
||||
public String aggregationKey() {
|
||||
return sourceHour + "\u0000" + sourceTopic + "\u0000" + kafkaPartition + "\u0000"
|
||||
+ policyVersion + "\u0000" + normalRetainBps + "\u0000" + nonNormalRetainBps;
|
||||
}
|
||||
|
||||
public LocalDateTime getSourceHour() { return sourceHour; }
|
||||
public String getSourceTopic() { return sourceTopic; }
|
||||
public int getKafkaPartition() { return kafkaPartition; }
|
||||
public String getPolicyVersion() { return policyVersion; }
|
||||
public int getNormalRetainBps() { return normalRetainBps; }
|
||||
public int getNonNormalRetainBps() { return nonNormalRetainBps; }
|
||||
public long getMessageTotal() { return messageTotal; }
|
||||
public long getAlarmRowsTotal() { return alarmRowsTotal; }
|
||||
public long getAlarmRowsSaved() { return alarmRowsSaved; }
|
||||
public long getNormalRowsTotal() { return normalRowsTotal; }
|
||||
public long getNormalRowsSaved() { return normalRowsSaved; }
|
||||
public long getNormalRowsDropped() { return normalRowsDropped; }
|
||||
public long getNonNormalRowsTotal() { return nonNormalRowsTotal; }
|
||||
public long getNonNormalRowsSaved() { return nonNormalRowsSaved; }
|
||||
public long getNonNormalRowsDropped() { return nonNormalRowsDropped; }
|
||||
public long getRawTotal() { return rawTotal; }
|
||||
public long getRawSaved() { return rawSaved; }
|
||||
public long getRawDropped() { return rawDropped; }
|
||||
public long getMinLagMs() { return minLagMs; }
|
||||
public long getMaxLagMs() { return maxLagMs; }
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.mapper.BacklogRetentionAuditMapper;
|
||||
import com.config.BacklogSamplingProperties;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** 消费优先:小时采样审计后台尽力保存,失败不改变采样决策,不等待主消费。 */
|
||||
@Slf4j
|
||||
@Service
|
||||
public class BacklogSamplingAuditService {
|
||||
private final BacklogRetentionAuditMapper mapper;
|
||||
private final BacklogSamplingProperties properties;
|
||||
private final BacklogSamplingMetrics metrics;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private volatile long retryAfterMs;
|
||||
private final BestEffortAuxiliaryQueue queue = new BestEffortAuxiliaryQueue("SAMPLING_AUDIT", 256, 50000, false);
|
||||
|
||||
@javax.annotation.PostConstruct public void start() { queue.start(); }
|
||||
@javax.annotation.PreDestroy public void stop() { queue.stop(); }
|
||||
public Map<String, Object> status() { return queue.status(); }
|
||||
|
||||
public BacklogSamplingAuditService(BacklogRetentionAuditMapper mapper,
|
||||
BacklogSamplingProperties properties,
|
||||
BacklogSamplingMetrics metrics,
|
||||
PlatformTransactionManager transactionManager) {
|
||||
this.mapper = mapper;
|
||||
this.properties = properties;
|
||||
this.metrics = metrics;
|
||||
this.transactionManager = transactionManager;
|
||||
}
|
||||
|
||||
/** 返回值仅代表入队是否成功,不影响调用方原采样决策。 */
|
||||
public boolean recordAsync(List<BacklogRetentionDelta> deltas) {
|
||||
if (deltas == null || deltas.isEmpty()) return true;
|
||||
long affectedMessages = 0L;
|
||||
try {
|
||||
affectedMessages = messageCount(deltas);
|
||||
final long taskMessages = affectedMessages;
|
||||
List<BacklogRetentionDelta> aggregated = aggregate(deltas);
|
||||
metrics.record(aggregated); // 决策指标,不再假称这些数字已写入审计数据库。
|
||||
if (System.currentTimeMillis() < retryAfterMs) {
|
||||
queue.loss("DATABASE_BACKOFF", null);
|
||||
metrics.auditLoss(affectedMessages);
|
||||
return false;
|
||||
}
|
||||
boolean offered = queue.offer(aggregated.size(), () -> writeAudit(aggregated, taskMessages));
|
||||
if (!offered) metrics.auditLoss(affectedMessages);
|
||||
return offered;
|
||||
} catch (RuntimeException failure) {
|
||||
queue.loss("PREPARE_FAILED", failure);
|
||||
metrics.auditLoss(affectedMessages);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void writeAudit(List<BacklogRetentionDelta> aggregated, long affectedMessages) {
|
||||
try {
|
||||
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
|
||||
transaction.setPropagationBehavior(org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
transaction.setTimeout(Math.max(1, properties.getAuditTimeoutSeconds()));
|
||||
transaction.execute(status -> {
|
||||
for (BacklogRetentionDelta delta : aggregated) mapper.upsert(delta);
|
||||
return null;
|
||||
});
|
||||
retryAfterMs = 0L;
|
||||
} catch (RuntimeException failure) {
|
||||
retryAfterMs = System.currentTimeMillis() + Math.max(1L, properties.getAuditRetryBackoffMs());
|
||||
queue.pause(properties.getAuditRetryBackoffMs());
|
||||
metrics.auditWriteFailed(affectedMessages);
|
||||
// 审计为累加UPSERT;提交结果不确定时自动重放可能双计数,当前选择记录损失而不重放。
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
static List<BacklogRetentionDelta> aggregate(List<BacklogRetentionDelta> deltas) {
|
||||
Map<String, BacklogRetentionDelta> grouped = new LinkedHashMap<>();
|
||||
for (BacklogRetentionDelta delta : deltas) {
|
||||
BacklogRetentionDelta existing = grouped.get(delta.aggregationKey());
|
||||
if (existing == null) grouped.put(delta.aggregationKey(), delta.copy());
|
||||
else existing.merge(delta);
|
||||
}
|
||||
return new ArrayList<>(grouped.values());
|
||||
}
|
||||
|
||||
private long messageCount(List<BacklogRetentionDelta> deltas) {
|
||||
long total = 0L;
|
||||
for (BacklogRetentionDelta delta : deltas) total += delta.getMessageTotal();
|
||||
return total;
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.common.service;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
|
||||
/** 积压采样热路径指标;表审计失败时仍可从接口和日志发现。 */
|
||||
@Component
|
||||
public class BacklogSamplingMetrics {
|
||||
private final LongAdder degradedMessages = new LongAdder();
|
||||
private final LongAdder alarmRowsSaved = new LongAdder();
|
||||
private final LongAdder normalRowsSaved = new LongAdder();
|
||||
private final LongAdder normalRowsDropped = new LongAdder();
|
||||
private final LongAdder nonNormalRowsSaved = new LongAdder();
|
||||
private final LongAdder nonNormalRowsDropped = new LongAdder();
|
||||
private final LongAdder rawSaved = new LongAdder();
|
||||
private final LongAdder rawDropped = new LongAdder();
|
||||
private final LongAdder auditWriteFailures = new LongAdder();
|
||||
private final LongAdder auditFallbackMessages = new LongAdder();
|
||||
private final LongAdder auditLostMessages = new LongAdder();
|
||||
|
||||
public void auditLoss(long messages) { auditLostMessages.add(Math.max(0L, messages)); }
|
||||
public void auditWriteFailed(long messages) { auditWriteFailures.increment(); auditLoss(messages); }
|
||||
|
||||
public void record(List<BacklogRetentionDelta> deltas) {
|
||||
for (BacklogRetentionDelta delta : deltas) {
|
||||
degradedMessages.add(delta.getMessageTotal());
|
||||
alarmRowsSaved.add(delta.getAlarmRowsSaved());
|
||||
normalRowsSaved.add(delta.getNormalRowsSaved());
|
||||
normalRowsDropped.add(delta.getNormalRowsDropped());
|
||||
nonNormalRowsSaved.add(delta.getNonNormalRowsSaved());
|
||||
nonNormalRowsDropped.add(delta.getNonNormalRowsDropped());
|
||||
rawSaved.add(delta.getRawSaved());
|
||||
rawDropped.add(delta.getRawDropped());
|
||||
}
|
||||
}
|
||||
|
||||
public void auditFailure(long affectedMessages) {
|
||||
auditWriteFailures.increment();
|
||||
auditFallbackMessages.add(Math.max(0L, affectedMessages));
|
||||
}
|
||||
|
||||
public Map<String, Object> snapshot() {
|
||||
Map<String, Object> values = new LinkedHashMap<>();
|
||||
values.put("degraded_messages_total", degradedMessages.sum());
|
||||
values.put("alarm_rows_saved_total", alarmRowsSaved.sum());
|
||||
values.put("normal_rows_saved_total", normalRowsSaved.sum());
|
||||
values.put("normal_rows_dropped_total", normalRowsDropped.sum());
|
||||
values.put("non_normal_rows_saved_total", nonNormalRowsSaved.sum());
|
||||
values.put("non_normal_rows_dropped_total", nonNormalRowsDropped.sum());
|
||||
values.put("raw_saved_total", rawSaved.sum());
|
||||
values.put("raw_dropped_total", rawDropped.sum());
|
||||
values.put("audit_write_failures_total", auditWriteFailures.sum());
|
||||
values.put("audit_fallback_messages_total", auditFallbackMessages.sum());
|
||||
values.put("audit_lost_or_unconfirmed_messages_total", auditLostMessages.sum());
|
||||
values.put("counter_semantics", "SAMPLING_DECISIONS_NOT_DB_CONFIRMATIONS");
|
||||
return values;
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package com.common.service;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/** 辅助写库专用有界队列。入队不执行任务、不等待数据库、不使用CallerRuns。 */
|
||||
@Slf4j
|
||||
final class BestEffortAuxiliaryQueue {
|
||||
private final String kind;
|
||||
private final ArrayBlockingQueue<Task> queue;
|
||||
private final long maxGroups;
|
||||
private final boolean retry;
|
||||
private final AtomicLong groups = new AtomicLong();
|
||||
private final AtomicLong accepted = new AtomicLong();
|
||||
private final AtomicLong completed = new AtomicLong();
|
||||
private final AtomicLong failures = new AtomicLong();
|
||||
private final AtomicLong lost = new AtomicLong();
|
||||
private final AtomicLong logAfter = new AtomicLong();
|
||||
private volatile Task current;
|
||||
private volatile boolean closed;
|
||||
private volatile long resumeAt;
|
||||
private ScheduledExecutorService executor;
|
||||
|
||||
BestEffortAuxiliaryQueue(String kind, int capacity, long maxGroups, boolean retry) {
|
||||
this.kind = kind;
|
||||
this.queue = new ArrayBlockingQueue<>(capacity);
|
||||
this.maxGroups = maxGroups;
|
||||
this.retry = retry;
|
||||
}
|
||||
|
||||
void start() {
|
||||
executor = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "syslog-aux-" + kind.toLowerCase(java.util.Locale.ROOT));
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
executor.scheduleWithFixedDelay(this::drain, 0, 200, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
boolean offer(int weight, Runnable work) {
|
||||
boolean reserved = false;
|
||||
try {
|
||||
if (closed || weight < 1) { loss("CLOSED_OR_INVALID", null); return false; }
|
||||
long value;
|
||||
do {
|
||||
value = groups.get();
|
||||
if (weight > maxGroups - value) { loss("GROUP_LIMIT", null); return false; }
|
||||
} while (!groups.compareAndSet(value, value + weight));
|
||||
reserved = true;
|
||||
if (!queue.offer(new Task(weight, work))) { loss("QUEUE_FULL", null); return false; }
|
||||
reserved = false;
|
||||
accepted.incrementAndGet();
|
||||
return true;
|
||||
} catch (RuntimeException failure) {
|
||||
loss("ENQUEUE_FAILED", failure);
|
||||
return false;
|
||||
} finally {
|
||||
if (reserved) groups.addAndGet(-weight);
|
||||
}
|
||||
}
|
||||
|
||||
// 只有后台线程/测试调用;入队和状态查询不获取该锁。
|
||||
synchronized void drain() {
|
||||
if (resumeAt != 0L && System.nanoTime() < resumeAt) return;
|
||||
for (int n = 0; n < 32 && !closed; n++) {
|
||||
if (current == null) current = queue.poll();
|
||||
Task task = current;
|
||||
if (task == null || (task.retryAt != 0L && System.nanoTime() < task.retryAt)) return;
|
||||
long begin = System.nanoTime();
|
||||
long queueMs = TimeUnit.NANOSECONDS.toMillis(begin - task.createdAt);
|
||||
try {
|
||||
task.work.run();
|
||||
completed.incrementAndGet();
|
||||
groups.addAndGet(-task.weight);
|
||||
current = null;
|
||||
long workMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin);
|
||||
if (workMs >= 500 || queueMs >= 500) log.warn(
|
||||
"[SLOW_SYSLOG_AUX] kind={}, groups={}, queueAgeMs={}, executeMs={}, status=SUCCESS",
|
||||
kind, task.weight, queueMs, workMs);
|
||||
} catch (RuntimeException failure) {
|
||||
failures.incrementAndGet();
|
||||
if (retry) {
|
||||
task.retryAt = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
|
||||
} else {
|
||||
groups.addAndGet(-task.weight);
|
||||
current = null;
|
||||
lost.incrementAndGet();
|
||||
}
|
||||
if (mayLog()) log.error("[SYSLOG_AUX_FAILURE] kind={}, groups={}, queueAgeMs={}, executeMs={}, "
|
||||
+ "action={}, failuresTotal={}", kind, task.weight, queueMs,
|
||||
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin),
|
||||
retry ? "BACKGROUND_RETRY" : "DROP_AUX_ONLY", failures.get(), failure);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void loss(String reason, RuntimeException failure) {
|
||||
lost.incrementAndGet();
|
||||
if (mayLog()) log.error("[SYSLOG_AUX_LOSS] kind={}, reason={}, lostTasksTotal={}, action=CONTINUE_FACT_CONSUMPTION",
|
||||
kind, reason, lost.get(), failure);
|
||||
}
|
||||
|
||||
void pause(long millis) {
|
||||
resumeAt = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(Math.max(1L, millis));
|
||||
}
|
||||
|
||||
private boolean mayLog() {
|
||||
long now = System.nanoTime();
|
||||
long after = logAfter.get();
|
||||
return (after == 0 || now >= after) && logAfter.compareAndSet(after, now + TimeUnit.SECONDS.toNanos(10));
|
||||
}
|
||||
|
||||
Map<String, Object> status() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("mode", "BEST_EFFORT_BACKGROUND");
|
||||
result.put("pending_tasks", queue.size() + (current == null ? 0 : 1));
|
||||
result.put("pending_groups", groups.get());
|
||||
result.put("max_groups", maxGroups);
|
||||
result.put("enqueued_total", accepted.get());
|
||||
result.put("completed_total", completed.get());
|
||||
result.put("failures_total", failures.get());
|
||||
result.put("lost_tasks_total", lost.get());
|
||||
return result;
|
||||
}
|
||||
|
||||
void stop() {
|
||||
closed = true;
|
||||
if (executor != null) executor.shutdownNow();
|
||||
if (groups.get() > 0) log.warn("[SYSLOG_AUX_SHUTDOWN_PENDING] kind={}, pendingGroups={}, action=AUX_DATA_MAY_BE_LOST",
|
||||
kind, groups.get());
|
||||
}
|
||||
|
||||
private static final class Task {
|
||||
final int weight;
|
||||
final Runnable work;
|
||||
final long createdAt = System.nanoTime();
|
||||
long retryAt;
|
||||
Task(int weight, Runnable work) { this.weight = weight; this.work = work; }
|
||||
}
|
||||
}
|
||||
+57
-37
@@ -21,11 +21,13 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.SortedMap;
|
||||
import java.util.TreeMap;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* 把当前事实事务的内存聚合结果直接写入小型统计表。
|
||||
* 把当前事实事务的内存聚合结果交给提交后的有界异步统计队列。
|
||||
*
|
||||
* <p>调用方必须已经开启事实事务;本类不会新开事务,也不会吞掉任何数据库异常。</p>
|
||||
* <p>DIRECT 连续消费优先,不写 Outbox 或统计表,统计异常记录后放行。
|
||||
* 历史 SHADOW 模式仍同步写影子投影,保留原有校验语义。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -63,6 +65,7 @@ public class DirectStatsProjectionWriter {
|
||||
private final StatsWriteModeProvider modeProvider;
|
||||
private final DirectStatsWriteMetrics metrics;
|
||||
private final StatsMaterializationPublisher materializationPublisher;
|
||||
private final StatsProjectionAsyncPublisher asyncPublisher;
|
||||
|
||||
@Value("${stats.incremental.read-enabled:false}")
|
||||
private boolean readEnabled;
|
||||
@@ -91,61 +94,52 @@ public class DirectStatsProjectionWriter {
|
||||
public DirectStatsProjectionWriter(JdbcTemplate jdbc,
|
||||
StatsWriteModeProvider modeProvider,
|
||||
DirectStatsWriteMetrics metrics,
|
||||
StatsMaterializationPublisher materializationPublisher) {
|
||||
StatsMaterializationPublisher materializationPublisher,
|
||||
StatsProjectionAsyncPublisher asyncPublisher) {
|
||||
this.jdbc = jdbc;
|
||||
this.modeProvider = modeProvider;
|
||||
this.metrics = metrics;
|
||||
this.materializationPublisher = materializationPublisher;
|
||||
this.asyncPublisher = asyncPublisher;
|
||||
}
|
||||
|
||||
public WriteResult writeStandardizedRows(List<Map<String, Object>> rows) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(rows == null ? 0 : rows.size());
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addStandardizedRows(rows);
|
||||
return write(accumulator, elapsedMs(aggregateStarted));
|
||||
return project(rows == null ? 0 : rows.size(), () -> accumulator().addStandardizedRows(rows), false);
|
||||
}
|
||||
|
||||
public WriteResult writeStandardizedRow(Map<String, Object> row) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(row == null ? 0 : 1);
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addStandardizedRow(row);
|
||||
return write(accumulator, elapsedMs(aggregateStarted));
|
||||
return project(row == null ? 0 : 1, () -> accumulator().addStandardizedRow(row), false);
|
||||
}
|
||||
|
||||
public WriteResult writeNonNormalRows(List<SyslogNonNormalMessage> messages) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(messages == null ? 0 : messages.size());
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addNonNormalRows(messages);
|
||||
return write(accumulator, elapsedMs(aggregateStarted));
|
||||
return project(messages == null ? 0 : messages.size(), () -> accumulator().addNonNormalRows(messages), false);
|
||||
}
|
||||
|
||||
public WriteResult writeNonNormalInsert(SyslogNonNormalMessage message) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(message == null ? 0 : 1);
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addNonNormalInsert(message);
|
||||
return write(accumulator, elapsedMs(aggregateStarted));
|
||||
return project(message == null ? 0 : 1, () -> accumulator().addNonNormalInsert(message), false);
|
||||
}
|
||||
|
||||
public WriteResult writeNonNormalUpdate(SyslogNonNormalMessage oldValue, SyslogNonNormalMessage patch) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(oldValue == null || patch == null ? 0 : 1);
|
||||
return project(oldValue == null || patch == null ? 0 : 1,
|
||||
() -> accumulator().addNonNormalUpdate(oldValue, patch), true);
|
||||
}
|
||||
|
||||
private WriteResult project(int rows, Supplier<DirectStatsAccumulator> build, boolean exact) {
|
||||
try {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(rows);
|
||||
}
|
||||
long started = System.nanoTime();
|
||||
DirectStatsAccumulator aggregate = build.get();
|
||||
return exact ? writeExactDeviceGroups(aggregate, elapsedMs(started))
|
||||
: write(aggregate, elapsedMs(started));
|
||||
} catch (RuntimeException failure) {
|
||||
if (!asynchronousProjection()) throw failure;
|
||||
metrics.recordFailure();
|
||||
asyncPublisher.recordLoss(rows, "AGGREGATION_OR_REGISTRATION_FAILED", failure);
|
||||
return WriteResult.inactive(rows);
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addNonNormalUpdate(oldValue, patch);
|
||||
return writeExactDeviceGroups(accumulator, elapsedMs(aggregateStarted));
|
||||
}
|
||||
|
||||
public void recordTransactionRetry() {
|
||||
@@ -160,6 +154,9 @@ public class DirectStatsProjectionWriter {
|
||||
status.put("today_stats_date_enabled", todayStatsDateEnabled);
|
||||
status.put("business_materialization_mode", asynchronousMaterialization()
|
||||
? "KAFKA_DIRTY_KEY" : "SYNCHRONOUS");
|
||||
status.put("daily_projection_write_mode", asynchronousProjection()
|
||||
? "BEST_EFFORT_AFTER_COMMIT_KAFKA" : "SYNCHRONOUS_MERGE");
|
||||
status.put("async_publisher", asyncPublisher.status());
|
||||
return status;
|
||||
}
|
||||
|
||||
@@ -194,6 +191,19 @@ public class DirectStatsProjectionWriter {
|
||||
}
|
||||
requireTransaction();
|
||||
|
||||
if (asynchronousProjection()) {
|
||||
long enqueueStarted = System.nanoTime();
|
||||
asyncPublisher.enqueueAfterCommit(StatsProjectionOutboxEvent.fromAccumulator(accumulator),
|
||||
accumulator.getInputRows());
|
||||
long enqueueMs = elapsedMs(enqueueStarted);
|
||||
int deviceGroups = effectiveDeviceEntries(accumulator).size();
|
||||
int ruleGroups = effectiveRuleEntries(accumulator).size();
|
||||
metrics.recordSuccess(accumulator.getInputRows(), deviceGroups, ruleGroups,
|
||||
aggregateMs, enqueueMs, 0L);
|
||||
return WriteResult.direct(accumulator.getInputRows(), deviceGroups, ruleGroups,
|
||||
aggregateMs, enqueueMs, 0L);
|
||||
}
|
||||
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta>> devices =
|
||||
effectiveDeviceEntries(accumulator);
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta>> rules =
|
||||
@@ -244,6 +254,11 @@ public class DirectStatsProjectionWriter {
|
||||
aggregateMs, 0L, 0L);
|
||||
}
|
||||
requireTransaction();
|
||||
// Additive positive/negative changes commute in the serialized projection consumer. This
|
||||
// keeps non-normal UPDATE statistics outside the fact transaction as well.
|
||||
if (asynchronousProjection()) {
|
||||
return write(accumulator, aggregateMs);
|
||||
}
|
||||
List<DirectStatsAccumulator.DailyKey> keys = new ArrayList<>(accumulator.getDevices().keySet());
|
||||
try {
|
||||
long mergeStarted = System.nanoTime();
|
||||
@@ -408,6 +423,11 @@ public class DirectStatsProjectionWriter {
|
||||
&& materializationPublisher.isEnabled();
|
||||
}
|
||||
|
||||
private boolean asynchronousProjection() {
|
||||
// 关闭统计发布也绝不回退同步统计SQL,以免再次阻塞事实消费。
|
||||
return modeProvider.getMode() == StatsWriteModeProvider.Mode.DIRECT;
|
||||
}
|
||||
|
||||
private List<StatsMaterializationCommand> materializationCommands(
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta>> devices,
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta>> rules) {
|
||||
|
||||
+20
-1
@@ -12,6 +12,12 @@ import java.util.concurrent.atomic.AtomicLong;
|
||||
public class DmDirectTransactionMetrics {
|
||||
private final AtomicLong transactions = new AtomicLong();
|
||||
private final AtomicLong factRows = new AtomicLong();
|
||||
private final AtomicLong jdbcPlanMs = new AtomicLong();
|
||||
private final AtomicLong jdbcPlanMaxMs = new AtomicLong();
|
||||
private final AtomicLong jdbcBindMs = new AtomicLong();
|
||||
private final AtomicLong jdbcBindMaxMs = new AtomicLong();
|
||||
private final AtomicLong jdbcExecuteMs = new AtomicLong();
|
||||
private final AtomicLong jdbcExecuteMaxMs = new AtomicLong();
|
||||
private final AtomicLong factFlushMs = new AtomicLong();
|
||||
private final AtomicLong factFlushMaxMs = new AtomicLong();
|
||||
private final AtomicLong commitMs = new AtomicLong();
|
||||
@@ -21,10 +27,17 @@ public class DmDirectTransactionMetrics {
|
||||
private final AtomicLong retries = new AtomicLong();
|
||||
private volatile LocalDateTime lastSuccessTime;
|
||||
|
||||
void recordSuccess(int rows, long flushDurationMs, long commitDurationMs,
|
||||
void recordSuccess(int rows, long planDurationMs, long bindDurationMs,
|
||||
long executeDurationMs, long flushDurationMs, long commitDurationMs,
|
||||
long transactionDurationMs) {
|
||||
transactions.incrementAndGet();
|
||||
factRows.addAndGet(rows);
|
||||
jdbcPlanMs.addAndGet(planDurationMs);
|
||||
updateMax(jdbcPlanMaxMs, planDurationMs);
|
||||
jdbcBindMs.addAndGet(bindDurationMs);
|
||||
updateMax(jdbcBindMaxMs, bindDurationMs);
|
||||
jdbcExecuteMs.addAndGet(executeDurationMs);
|
||||
updateMax(jdbcExecuteMaxMs, executeDurationMs);
|
||||
factFlushMs.addAndGet(flushDurationMs);
|
||||
updateMax(factFlushMaxMs, flushDurationMs);
|
||||
commitMs.addAndGet(commitDurationMs);
|
||||
@@ -42,6 +55,12 @@ public class DmDirectTransactionMetrics {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("transactions", transactions.get());
|
||||
result.put("fact_rows", factRows.get());
|
||||
result.put("jdbc_plan_duration_ms_total", jdbcPlanMs.get());
|
||||
result.put("jdbc_plan_duration_ms_max", jdbcPlanMaxMs.get());
|
||||
result.put("jdbc_bind_duration_ms_total", jdbcBindMs.get());
|
||||
result.put("jdbc_bind_duration_ms_max", jdbcBindMaxMs.get());
|
||||
result.put("jdbc_execute_duration_ms_total", jdbcExecuteMs.get());
|
||||
result.put("jdbc_execute_duration_ms_max", jdbcExecuteMaxMs.get());
|
||||
result.put("fact_flush_duration_ms_total", factFlushMs.get());
|
||||
result.put("fact_flush_duration_ms_max", factFlushMaxMs.get());
|
||||
result.put("commit_duration_ms_total", commitMs.get());
|
||||
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
import com.common.util.Utf8TextTruncator;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
|
||||
/** 达梦持久化边界的大字段保护;0 表示兼容模式下不限制。 */
|
||||
@Component
|
||||
public class DmLargeTextLimiter {
|
||||
private static final long MIN_ENABLED_LIMIT = 64L;
|
||||
|
||||
@Value("${dm.normal.large-field-max-utf8-bytes:262144}")
|
||||
private long normalMaxBytes;
|
||||
|
||||
@Value("${dm.normal.large-fields:http_req_body,http_resp_body,http_req_header,http_resp_header,detail,description,cmdline,shell_cmdline,parent_cmdline,mail_message}")
|
||||
private String normalFieldsValue;
|
||||
|
||||
@Value("${dm.non-normal.large-field-max-utf8-bytes:262144}")
|
||||
private long nonNormalMaxBytes;
|
||||
|
||||
private volatile Set<String> normalFields = Collections.emptySet();
|
||||
private final LongAdder normalFieldsTruncated = new LongAdder();
|
||||
private final LongAdder nonNormalFieldsTruncated = new LongAdder();
|
||||
|
||||
@PostConstruct
|
||||
public void validate() {
|
||||
validateLimit(normalMaxBytes, "dm.normal.large-field-max-utf8-bytes");
|
||||
validateLimit(nonNormalMaxBytes, "dm.non-normal.large-field-max-utf8-bytes");
|
||||
Set<String> parsed = new LinkedHashSet<>();
|
||||
if (normalFieldsValue != null) {
|
||||
Arrays.stream(normalFieldsValue.split(","))
|
||||
.map(String::trim).filter(value -> !value.isEmpty()).forEach(parsed::add);
|
||||
}
|
||||
normalFields = Collections.unmodifiableSet(parsed);
|
||||
}
|
||||
|
||||
private static void validateLimit(long value, String name) {
|
||||
if (value < 0L || (value > 0L && value < MIN_ENABLED_LIMIT)) {
|
||||
throw new IllegalArgumentException(name + " 必须为 0 或至少 " + MIN_ENABLED_LIMIT);
|
||||
}
|
||||
}
|
||||
|
||||
public void truncateNormalRow(Map<String, Object> row) {
|
||||
if (row == null || normalMaxBytes == 0L) return;
|
||||
for (String field : normalFields) {
|
||||
Object value = row.get(field);
|
||||
if (!(value instanceof String)) continue;
|
||||
Utf8TextTruncator.Result result = Utf8TextTruncator.truncate((String) value, normalMaxBytes);
|
||||
if (result.isTruncated()) {
|
||||
row.put(field, result.getValue());
|
||||
normalFieldsTruncated.increment();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void truncateNonNormal(SyslogNonNormalMessage message) {
|
||||
if (message == null || nonNormalMaxBytes == 0L) return;
|
||||
message.setSyslogMessage(truncateNonNormalValue(message.getSyslogMessage()));
|
||||
message.setHeaderMessage(truncateNonNormalValue(message.getHeaderMessage()));
|
||||
message.setReasonDetail(truncateNonNormalValue(message.getReasonDetail()));
|
||||
}
|
||||
|
||||
private String truncateNonNormalValue(String value) {
|
||||
Utf8TextTruncator.Result result = Utf8TextTruncator.truncate(value, nonNormalMaxBytes);
|
||||
if (result.isTruncated()) nonNormalFieldsTruncated.increment();
|
||||
return result.getValue();
|
||||
}
|
||||
|
||||
public long getNormalFieldsTruncated() { return normalFieldsTruncated.sum(); }
|
||||
public long getNonNormalFieldsTruncated() { return nonNormalFieldsTruncated.sum(); }
|
||||
|
||||
/** 测试和非 Spring 兼容入口。 */
|
||||
static DmLargeTextLimiter unlimited() {
|
||||
DmLargeTextLimiter limiter = new DmLargeTextLimiter();
|
||||
limiter.normalMaxBytes = 0L;
|
||||
limiter.nonNormalMaxBytes = 0L;
|
||||
limiter.validate();
|
||||
return limiter;
|
||||
}
|
||||
}
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
package com.common.service;
|
||||
|
||||
import org.springframework.jdbc.core.ConnectionCallback;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
/**
|
||||
* 使用一个固定 {@link PreparedStatement} 写入一批标准化事实。
|
||||
*
|
||||
* <p>字段白名单和 NULL 的 JDBC 类型从目标表元数据读取并缓存。每个批次只根据字段并集生成
|
||||
* 一次 INSERT,后续每行只绑定参数和 {@code addBatch()},避免 MyBatis 动态 XML 为每行执行
|
||||
* 数百次 OGNL 表达式和反射方法查找。</p>
|
||||
*/
|
||||
@Component
|
||||
public class DmPreparedBatchInserter {
|
||||
|
||||
static final String NORMAL_TABLE = "syslog_normal_data";
|
||||
static final String ALARM_TABLE = "syslog_normal_alarm";
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final ConcurrentMap<String, TableMetadata> metadataCache = new ConcurrentHashMap<>();
|
||||
|
||||
public DmPreparedBatchInserter(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
public BatchExecution insert(boolean alarmTable, List<Map<String, Object>> rows,
|
||||
int statementTimeoutSeconds) {
|
||||
return insert(alarmTable, rows, statementTimeoutSeconds, new DmWriteSizeEstimate());
|
||||
}
|
||||
|
||||
BatchExecution insert(boolean alarmTable, List<Map<String, Object>> rows,
|
||||
int statementTimeoutSeconds, DmWriteSizeEstimate writeSize) {
|
||||
if (rows == null || rows.isEmpty()) {
|
||||
return BatchExecution.EMPTY;
|
||||
}
|
||||
final String table = alarmTable ? ALARM_TABLE : NORMAL_TABLE;
|
||||
return jdbcTemplate.execute((ConnectionCallback<BatchExecution>) connection ->
|
||||
execute(connection, table, rows, statementTimeoutSeconds, writeSize));
|
||||
}
|
||||
|
||||
BatchExecution execute(Connection connection, String table, List<Map<String, Object>> rows,
|
||||
int statementTimeoutSeconds) throws SQLException {
|
||||
return execute(connection, table, rows, statementTimeoutSeconds, new DmWriteSizeEstimate());
|
||||
}
|
||||
|
||||
BatchExecution execute(Connection connection, String table, List<Map<String, Object>> rows,
|
||||
int statementTimeoutSeconds, DmWriteSizeEstimate writeSize) throws SQLException {
|
||||
long planStarted = System.nanoTime();
|
||||
TableMetadata metadata = metadata(connection, table);
|
||||
BatchPlan plan = buildPlan(table, rows, metadata);
|
||||
long planMs = elapsedMillis(planStarted);
|
||||
// 使用元数据白名单选中的列,排除规则携带但不会实际绑定的字段。
|
||||
// 执行前完成测量,使JDBC绑定/执行失败时仍可输出这次尝试的数据量。
|
||||
writeSize.measure(rows, plan.columns);
|
||||
|
||||
long bindMs;
|
||||
long executeMs;
|
||||
try (PreparedStatement statement = connection.prepareStatement(plan.sql)) {
|
||||
statement.setQueryTimeout(Math.max(1, statementTimeoutSeconds));
|
||||
long bindStarted = System.nanoTime();
|
||||
for (Map<String, Object> row : rows) {
|
||||
bindRow(statement, row, plan.columns);
|
||||
statement.addBatch();
|
||||
}
|
||||
bindMs = elapsedMillis(bindStarted);
|
||||
|
||||
long executeStarted = System.nanoTime();
|
||||
int[] results = statement.executeBatch();
|
||||
executeMs = elapsedMillis(executeStarted);
|
||||
rejectFailedResult(results);
|
||||
}
|
||||
return new BatchExecution(rows.size(), plan.columns.size(), planMs, bindMs, executeMs);
|
||||
}
|
||||
|
||||
private TableMetadata metadata(Connection connection, String table) throws SQLException {
|
||||
TableMetadata cached = metadataCache.get(table);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
TableMetadata loaded = loadMetadata(connection, table);
|
||||
TableMetadata raced = metadataCache.putIfAbsent(table, loaded);
|
||||
return raced == null ? loaded : raced;
|
||||
}
|
||||
|
||||
private static TableMetadata loadMetadata(Connection connection, String table) throws SQLException {
|
||||
validateIdentifier(table);
|
||||
List<ColumnMetadata> columns = new ArrayList<>();
|
||||
try (PreparedStatement statement = connection.prepareStatement(
|
||||
"SELECT * FROM " + table + " WHERE 1=0");
|
||||
ResultSet resultSet = statement.executeQuery()) {
|
||||
ResultSetMetaData metadata = resultSet.getMetaData();
|
||||
for (int index = 1; index <= metadata.getColumnCount(); index++) {
|
||||
String name = metadata.getColumnName(index);
|
||||
validateIdentifier(name);
|
||||
columns.add(new ColumnMetadata(name.toLowerCase(Locale.ROOT), metadata.getColumnType(index)));
|
||||
}
|
||||
}
|
||||
if (columns.isEmpty()) {
|
||||
throw new SQLException("目标表没有可写字段: " + table);
|
||||
}
|
||||
return new TableMetadata(columns);
|
||||
}
|
||||
|
||||
static BatchPlan buildPlan(String table, List<Map<String, Object>> rows, TableMetadata metadata) {
|
||||
validateIdentifier(table);
|
||||
Set<String> requestedColumns = new HashSet<>();
|
||||
for (Map<String, Object> row : rows) {
|
||||
if (row == null) {
|
||||
throw new IllegalArgumentException("达梦批写行不能为空");
|
||||
}
|
||||
for (Map.Entry<String, Object> entry : row.entrySet()) {
|
||||
if (entry.getKey() != null && entry.getValue() != null) {
|
||||
// 标准化字段契约使用小写 snake_case;与旧 Mapper 一致,未知或大小写错误的键忽略。
|
||||
requestedColumns.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<ColumnMetadata> selected = new ArrayList<>();
|
||||
for (ColumnMetadata column : metadata.columns) {
|
||||
if (requestedColumns.contains(column.name)) {
|
||||
selected.add(column);
|
||||
}
|
||||
}
|
||||
if (selected.isEmpty()) {
|
||||
throw new IllegalArgumentException("达梦批写没有目标表允许的非空字段: " + table);
|
||||
}
|
||||
|
||||
StringBuilder sql = new StringBuilder(64 + selected.size() * 12);
|
||||
sql.append("INSERT INTO ").append(table).append(" (");
|
||||
for (int index = 0; index < selected.size(); index++) {
|
||||
if (index > 0) sql.append(',');
|
||||
sql.append(selected.get(index).name);
|
||||
}
|
||||
sql.append(") VALUES (");
|
||||
for (int index = 0; index < selected.size(); index++) {
|
||||
if (index > 0) sql.append(',');
|
||||
sql.append('?');
|
||||
}
|
||||
sql.append(')');
|
||||
return new BatchPlan(sql.toString(), selected);
|
||||
}
|
||||
|
||||
static void bindRow(PreparedStatement statement, Map<String, Object> row,
|
||||
List<ColumnMetadata> columns) throws SQLException {
|
||||
for (int index = 0; index < columns.size(); index++) {
|
||||
ColumnMetadata column = columns.get(index);
|
||||
Object value = row.get(column.name);
|
||||
int parameterIndex = index + 1;
|
||||
if (value == null) {
|
||||
statement.setNull(parameterIndex, column.jdbcType);
|
||||
} else if (value instanceof Timestamp) {
|
||||
statement.setTimestamp(parameterIndex, (Timestamp) value);
|
||||
} else if (value instanceof java.sql.Date) {
|
||||
statement.setDate(parameterIndex, (java.sql.Date) value);
|
||||
} else if (value instanceof java.sql.Time) {
|
||||
statement.setTime(parameterIndex, (java.sql.Time) value);
|
||||
} else if (value instanceof java.util.Date) {
|
||||
statement.setTimestamp(parameterIndex,
|
||||
new Timestamp(((java.util.Date) value).getTime()));
|
||||
} else if (value instanceof LocalDateTime) {
|
||||
statement.setTimestamp(parameterIndex, Timestamp.valueOf((LocalDateTime) value));
|
||||
} else if (value instanceof LocalDate) {
|
||||
statement.setDate(parameterIndex, java.sql.Date.valueOf((LocalDate) value));
|
||||
} else if (value instanceof byte[]) {
|
||||
statement.setBytes(parameterIndex, (byte[]) value);
|
||||
} else {
|
||||
statement.setObject(parameterIndex, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejectFailedResult(int[] results) throws SQLException {
|
||||
if (results == null) return;
|
||||
for (int result : results) {
|
||||
if (result == Statement.EXECUTE_FAILED) {
|
||||
throw new SQLException("达梦 JDBC batch 返回 EXECUTE_FAILED");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateIdentifier(String identifier) {
|
||||
if (identifier == null || !identifier.matches("[A-Za-z_][A-Za-z0-9_$#]*")) {
|
||||
throw new IllegalArgumentException("非法达梦标识符: " + identifier);
|
||||
}
|
||||
}
|
||||
|
||||
private static long elapsedMillis(long startedAt) {
|
||||
return (System.nanoTime() - startedAt) / 1_000_000L;
|
||||
}
|
||||
|
||||
static final class TableMetadata {
|
||||
final List<ColumnMetadata> columns;
|
||||
|
||||
TableMetadata(List<ColumnMetadata> columns) {
|
||||
this.columns = Collections.unmodifiableList(new ArrayList<>(columns));
|
||||
}
|
||||
|
||||
static TableMetadata of(Map<String, Integer> columns) {
|
||||
List<ColumnMetadata> result = new ArrayList<>();
|
||||
for (Map.Entry<String, Integer> entry : new LinkedHashMap<>(columns).entrySet()) {
|
||||
result.add(new ColumnMetadata(entry.getKey().toLowerCase(Locale.ROOT), entry.getValue()));
|
||||
}
|
||||
return new TableMetadata(result);
|
||||
}
|
||||
}
|
||||
|
||||
static final class ColumnMetadata {
|
||||
final String name;
|
||||
final int jdbcType;
|
||||
|
||||
ColumnMetadata(String name, int jdbcType) {
|
||||
validateIdentifier(name);
|
||||
this.name = name.toLowerCase(Locale.ROOT);
|
||||
this.jdbcType = jdbcType;
|
||||
}
|
||||
}
|
||||
|
||||
static final class BatchPlan {
|
||||
final String sql;
|
||||
final List<ColumnMetadata> columns;
|
||||
|
||||
BatchPlan(String sql, List<ColumnMetadata> columns) {
|
||||
this.sql = sql;
|
||||
this.columns = Collections.unmodifiableList(new ArrayList<>(columns));
|
||||
}
|
||||
}
|
||||
|
||||
public static final class BatchExecution {
|
||||
static final BatchExecution EMPTY = new BatchExecution(0, 0, 0L, 0L, 0L);
|
||||
private final int rows;
|
||||
private final int columns;
|
||||
private final long planMs;
|
||||
private final long bindMs;
|
||||
private final long executeMs;
|
||||
|
||||
BatchExecution(int rows, int columns, long planMs, long bindMs, long executeMs) {
|
||||
this.rows = rows;
|
||||
this.columns = columns;
|
||||
this.planMs = planMs;
|
||||
this.bindMs = bindMs;
|
||||
this.executeMs = executeMs;
|
||||
}
|
||||
|
||||
public int getRows() { return rows; }
|
||||
public int getColumns() { return columns; }
|
||||
public long getPlanMs() { return planMs; }
|
||||
public long getBindMs() { return bindMs; }
|
||||
public long getExecuteMs() { return executeMs; }
|
||||
}
|
||||
}
|
||||
+73
-76
@@ -1,7 +1,5 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.mapper.SyslogNormalAlarmMapper;
|
||||
import com.common.mapper.SyslogNormalDataMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.session.ExecutorType;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
@@ -13,20 +11,15 @@ import org.springframework.transaction.support.TransactionSynchronizationAdapter
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 在一个达梦小事务中执行真正的 MyBatis JDBC batch。
|
||||
* 在一个达梦小事务中执行标准化事实的直接 JDBC batch。
|
||||
*
|
||||
* <p>这个类只负责数据库执行,不负责错误分类、拆分或 Kafka 状态。上层写入器保证传入的所有行
|
||||
* 普通日志和告警日志分别使用当前小批次的非空字段并集模板,因此同一目标表、同一分区日期内
|
||||
* MyBatis BatchExecutor 可以复用同一个 PreparedStatement。
|
||||
* 每个 {@link #execute(boolean, List, int)} 调用都会创建独立事务;失败时整个小批次回滚,上层随后
|
||||
* 决定二分定位还是按系统故障停止。</p>
|
||||
* <p>事实表每批只生成一个固定 PreparedStatement,避免逐行解析大型 MyBatis 动态 XML;仅在旧增量
|
||||
* 捕获兼容开关开启时使用 BATCH SqlSession 追加变更日志。每个
|
||||
* {@link #execute(boolean, List, int)} 调用都会创建独立事务;失败时整个小批次回滚,上层随后决定
|
||||
* 二分定位还是按系统故障停止。</p>
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
@@ -34,6 +27,7 @@ public class DmStandardizedBatchExecutor {
|
||||
|
||||
private final SqlSessionTemplate batchSqlSession;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private final DmPreparedBatchInserter preparedBatchInserter;
|
||||
private final StatsChangeCaptureService statsChangeCaptureService;
|
||||
private final DirectStatsProjectionWriter directStatsProjectionWriter;
|
||||
private final DmDirectTransactionMetrics transactionMetrics;
|
||||
@@ -42,6 +36,9 @@ public class DmStandardizedBatchExecutor {
|
||||
@org.springframework.beans.factory.annotation.Value("${stats.direct.transaction-log-enabled:false}")
|
||||
private boolean transactionLogEnabled;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Value("${syslog.slow-batch.threshold-ms:1000}")
|
||||
private long slowTransactionThresholdMs;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Value("${stats.direct.max-concurrency-retries:1}")
|
||||
private int maxConcurrencyRetries;
|
||||
|
||||
@@ -50,14 +47,15 @@ public class DmStandardizedBatchExecutor {
|
||||
|
||||
public DmStandardizedBatchExecutor(SqlSessionFactory sqlSessionFactory,
|
||||
PlatformTransactionManager transactionManager,
|
||||
DmPreparedBatchInserter preparedBatchInserter,
|
||||
StatsChangeCaptureService statsChangeCaptureService,
|
||||
DirectStatsProjectionWriter directStatsProjectionWriter,
|
||||
DmDirectTransactionMetrics transactionMetrics,
|
||||
LateAlarmBucketWriter lateAlarmBucketWriter) {
|
||||
// SqlSessionTemplate 本身线程安全。ExecutorType.BATCH 会把相同 SQL 的参数暂存在当前事务会话中,
|
||||
// 直到 flushStatements()/commit 时才真正交给 JDBC 驱动批量执行。
|
||||
// 该 BATCH Session 仅供旧统计变更日志兼容链路使用;事实行由 preparedBatchInserter 直接批写。
|
||||
this.batchSqlSession = new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH);
|
||||
this.transactionManager = transactionManager;
|
||||
this.preparedBatchInserter = preparedBatchInserter;
|
||||
this.statsChangeCaptureService = statsChangeCaptureService;
|
||||
this.directStatsProjectionWriter = directStatsProjectionWriter;
|
||||
this.transactionMetrics = transactionMetrics;
|
||||
@@ -77,11 +75,10 @@ public class DmStandardizedBatchExecutor {
|
||||
return;
|
||||
}
|
||||
|
||||
List<Map<String, Object>> alignedRows = alignBatchColumns(rows);
|
||||
int attempt = 0;
|
||||
while (true) {
|
||||
try {
|
||||
executeTransaction(alarmTable, alignedRows, transactionTimeoutSeconds, attempt);
|
||||
executeTransaction(alarmTable, rows, transactionTimeoutSeconds, attempt);
|
||||
return;
|
||||
} catch (DirectStatsProjectionWriter.ConcurrentStatsWriteException concurrentFailure) {
|
||||
if (attempt >= Math.max(0, maxConcurrencyRetries)) {
|
||||
@@ -95,39 +92,6 @@ public class DmStandardizedBatchExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算当前小批次所有非空字段的并集,并为每行建立相同键集合的浅拷贝。
|
||||
*
|
||||
* <p>Mapper XML 只允许声明过的列,额外业务键即使出现在 Map 中也不会进入 SQL。
|
||||
* 同一键在某行不存在时,Map#get 返回 null,最终由 JDBC 按 SQL NULL 绑定。</p>
|
||||
*/
|
||||
static List<Map<String, Object>> alignBatchColumns(List<Map<String, Object>> rows) {
|
||||
Set<String> columnUnion = new LinkedHashSet<>();
|
||||
for (Map<String, Object> row : rows) {
|
||||
if (row == null) {
|
||||
throw new IllegalArgumentException("达梦批写行不能为空");
|
||||
}
|
||||
for (Map.Entry<String, Object> entry : row.entrySet()) {
|
||||
if (entry.getKey() != null && entry.getValue() != null) {
|
||||
columnUnion.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (columnUnion.isEmpty()) {
|
||||
throw new IllegalArgumentException("达梦批写没有可插入的非空字段");
|
||||
}
|
||||
|
||||
List<Map<String, Object>> alignedRows = new ArrayList<>(rows.size());
|
||||
for (Map<String, Object> row : rows) {
|
||||
Map<String, Object> aligned = new LinkedHashMap<>(columnUnion.size());
|
||||
for (String column : columnUnion) {
|
||||
aligned.put(column, row.get(column));
|
||||
}
|
||||
alignedRows.add(aligned);
|
||||
}
|
||||
return alignedRows;
|
||||
}
|
||||
|
||||
private void executeTransaction(boolean alarmTable, List<Map<String, Object>> rows,
|
||||
int transactionTimeoutSeconds, int retries) {
|
||||
|
||||
@@ -135,11 +99,14 @@ public class DmStandardizedBatchExecutor {
|
||||
transaction.setTimeout(Math.max(1, transactionTimeoutSeconds));
|
||||
long transactionStarted = System.nanoTime();
|
||||
final TransactionTiming timing = new TransactionTiming();
|
||||
try {
|
||||
transaction.execute(status -> {
|
||||
timing.beginMs = elapsedMs(transactionStarted);
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
|
||||
@Override
|
||||
public void beforeCommit(boolean readOnly) {
|
||||
timing.commitStarted = System.nanoTime();
|
||||
timing.phase("FACT_COMMIT");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -147,52 +114,74 @@ public class DmStandardizedBatchExecutor {
|
||||
timing.commitMs = elapsedMs(timing.commitStarted);
|
||||
}
|
||||
});
|
||||
if (alarmTable) {
|
||||
SyslogNormalAlarmMapper mapper = batchSqlSession.getMapper(SyslogNormalAlarmMapper.class);
|
||||
for (Map<String, Object> row : rows) {
|
||||
// BatchExecutor 下这里不会逐条提交;返回值也不是最终影响行数,不能据此判断成功。
|
||||
mapper.insertBatchPlanned(row);
|
||||
}
|
||||
} else {
|
||||
SyslogNormalDataMapper mapper = batchSqlSession.getMapper(SyslogNormalDataMapper.class);
|
||||
for (Map<String, Object> row : rows) {
|
||||
mapper.insertBatchPlanned(row);
|
||||
}
|
||||
}
|
||||
|
||||
// 与事实行共用当前达梦事务;任一变更日志写入失败都会使整批事实回滚。
|
||||
statsChangeCaptureService.captureStandardizedBatch(batchSqlSession, rows, alarmTable);
|
||||
|
||||
// 先 flush 事实和兼容期变更日志,让唯一键、类型和分区错误在统计增量前暴露。
|
||||
long flushStarted = System.nanoTime();
|
||||
batchSqlSession.flushStatements();
|
||||
// 事实表使用一个固定 PreparedStatement 直接 addBatch,彻底绕开逐行 OGNL 动态 SQL。
|
||||
timing.phase("JDBC_FACT_WRITE");
|
||||
timing.batchExecution = preparedBatchInserter.insert(
|
||||
alarmTable, rows, transactionTimeoutSeconds, timing.writeSize);
|
||||
|
||||
// 兼容期变更日志仍与事实行共用当前事务;默认关闭时完全不创建 MyBatis BatchSession。
|
||||
if (statsChangeCaptureService.isEnabled()) {
|
||||
timing.phase("LEGACY_STATS_CAPTURE");
|
||||
statsChangeCaptureService.captureStandardizedBatch(batchSqlSession, rows, alarmTable);
|
||||
batchSqlSession.flushStatements();
|
||||
}
|
||||
timing.factFlushMs = elapsedMs(flushStarted);
|
||||
|
||||
// 与标准化告警事实共用同一事务写入事件时间桶。事实成功而通知失败时必须整体回滚,
|
||||
// 否则迟到数据可能永久失去重放机会。
|
||||
// 只注册提交后入队;分钟桶在独立后台事务写入,失败不回滚当前告警。
|
||||
if (alarmTable) {
|
||||
timing.phase("LATE_BUCKET_REGISTER");
|
||||
long bucketStarted = System.nanoTime();
|
||||
lateAlarmBucketWriter.record(rows);
|
||||
timing.lateBucketMs = elapsedMs(bucketStarted);
|
||||
}
|
||||
|
||||
// DIRECT/SHADOW 模式在当前事务内按设备、规则聚合写统计;LEGACY 模式会直接返回。
|
||||
// 任一统计 SQL 失败都会回滚本事务的事实行,禁止产生无法定位的统计缺口。
|
||||
// DIRECT 只聚合并注册afterCommit入队;此处不写Outbox/统计表、不发送Kafka。
|
||||
// 独立后台线程发送统计事件,失败不影响事实提交;历史SHADOW模式保留同步MERGE。
|
||||
timing.phase("STATS_REGISTER");
|
||||
timing.statsResult = directStatsProjectionWriter.writeStandardizedRows(rows);
|
||||
return null;
|
||||
});
|
||||
} catch (RuntimeException failure) {
|
||||
log.error("[SLOW_DM_TRANSACTION] batchId={}, table={}, factRows={}, status=FAILED, "
|
||||
+ "failureStage={}, phaseElapsedMs={}, transactionMs={}, connectionBeginMs={}, "
|
||||
+ "jdbcExecuteMs={}, lateAlarmBucketMs={}, retry={}, errorType={}, {}",
|
||||
org.slf4j.MDC.get("syslogBatchId"), alarmTable ? "syslog_normal_alarm" : "syslog_normal_data",
|
||||
rows.size(), timing.phase, elapsedMs(timing.phaseStarted), elapsedMs(transactionStarted),
|
||||
timing.beginMs, timing.batchExecution.getExecuteMs(), timing.lateBucketMs, retries,
|
||||
failure.getClass().getName(), timing.writeSize);
|
||||
throw failure;
|
||||
}
|
||||
long transactionMs = elapsedMs(transactionStarted);
|
||||
transactionMetrics.recordSuccess(rows.size(), timing.factFlushMs, timing.commitMs, transactionMs);
|
||||
transactionMetrics.recordSuccess(rows.size(), timing.batchExecution.getPlanMs(),
|
||||
timing.batchExecution.getBindMs(), timing.batchExecution.getExecuteMs(),
|
||||
timing.factFlushMs, timing.commitMs, transactionMs);
|
||||
if (slowTransactionThresholdMs > 0 && transactionMs >= slowTransactionThresholdMs) {
|
||||
log.warn("[SLOW_DM_TRANSACTION] batchId={}, table={}, factRows={}, status=SUCCESS, connectionBeginMs={}, jdbcPlanMs={}, "
|
||||
+ "jdbcBindMs={}, jdbcExecuteMs={}, lateAlarmBucketMs={}, statsProjectionStageMs={}, "
|
||||
+ "commitMs={}, transactionMs={}, retry={}, {}",
|
||||
org.slf4j.MDC.get("syslogBatchId"), alarmTable ? "syslog_normal_alarm" : "syslog_normal_data", rows.size(), timing.beginMs,
|
||||
timing.batchExecution.getPlanMs(), timing.batchExecution.getBindMs(),
|
||||
timing.batchExecution.getExecuteMs(), timing.lateBucketMs,
|
||||
timing.statsResult == null ? 0L : timing.statsResult.getMergeMs(),
|
||||
timing.commitMs, transactionMs, retries, timing.writeSize);
|
||||
}
|
||||
if (transactionLogEnabled && timing.statsResult != null && timing.statsResult.isDirect()) {
|
||||
log.info("DIRECT 达梦事务完成: factRows={}, deviceGroups={}, ruleGroups={}, aggregateMs={}, " +
|
||||
"factFlushMs={}, statsMergeMs={}, materializeMs={}, commitMs={}, transactionMs={}, retry={}",
|
||||
"jdbcPlanMs={}, jdbcBindMs={}, jdbcExecuteMs={}, factFlushMs={}, "
|
||||
+ "statsProjectionStageMs={}, materializeMs={}, commitMs={}, transactionMs={}, retry={}, {}",
|
||||
rows.size(), timing.statsResult.getDeviceGroups(), timing.statsResult.getRuleGroups(),
|
||||
timing.statsResult.getAggregateMs(), timing.factFlushMs,
|
||||
timing.statsResult.getAggregateMs(), timing.batchExecution.getPlanMs(),
|
||||
timing.batchExecution.getBindMs(), timing.batchExecution.getExecuteMs(), timing.factFlushMs,
|
||||
timing.statsResult.getMergeMs(), timing.statsResult.getMaterializeMs(),
|
||||
timing.commitMs, transactionMs, retries);
|
||||
timing.commitMs, transactionMs, retries, timing.writeSize);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
return transactionMetrics.snapshot();
|
||||
Map<String, Object> result = transactionMetrics.snapshot();
|
||||
result.put("late_alarm_bucket_async", lateAlarmBucketWriter.status());
|
||||
return result;
|
||||
}
|
||||
|
||||
private static long elapsedMs(long startedNanos) {
|
||||
@@ -200,9 +189,17 @@ public class DmStandardizedBatchExecutor {
|
||||
}
|
||||
|
||||
private static final class TransactionTiming {
|
||||
private final DmWriteSizeEstimate writeSize = new DmWriteSizeEstimate();
|
||||
private String phase = "CONNECTION_BEGIN";
|
||||
private long phaseStarted = System.nanoTime();
|
||||
private void phase(String value) { phase = value; phaseStarted = System.nanoTime(); }
|
||||
private long beginMs;
|
||||
private long lateBucketMs;
|
||||
private long factFlushMs;
|
||||
private long commitStarted;
|
||||
private long commitMs;
|
||||
private DmPreparedBatchInserter.BatchExecution batchExecution =
|
||||
DmPreparedBatchInserter.BatchExecution.EMPTY;
|
||||
private DirectStatsProjectionWriter.WriteResult statsResult;
|
||||
}
|
||||
|
||||
|
||||
+32
-2
@@ -60,14 +60,18 @@ public class DmStandardizedBatchWriter {
|
||||
private final SyslogNormalDataService normalDataService;
|
||||
private final DmStandardizedBatchExecutor batchExecutor;
|
||||
private final Executor writerExecutor;
|
||||
private final DmLargeTextLimiter largeTextLimiter;
|
||||
|
||||
// 未配置时直接启用本次改造的批写路径;SINGLE 只作为现场故障回退开关保留。
|
||||
@Value("${dm.standardized-write.mode:BATCH}")
|
||||
private String mode;
|
||||
|
||||
@Value("${dm.standardized-write.batch-size:500}")
|
||||
@Value("${dm.standardized-write.batch-size:2000}")
|
||||
private int batchSize;
|
||||
|
||||
@Value("${syslog.slow-batch.threshold-ms:1000}")
|
||||
private long slowQueueThresholdMs;
|
||||
|
||||
@Value("${dm.standardized-write.transaction-timeout-seconds:45}")
|
||||
private int transactionTimeoutSeconds;
|
||||
|
||||
@@ -89,12 +93,22 @@ public class DmStandardizedBatchWriter {
|
||||
private final AtomicInteger consecutiveSystemFailures = new AtomicInteger();
|
||||
private volatile long circuitOpenUntilMs;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
public DmStandardizedBatchWriter(SyslogNormalDataService normalDataService,
|
||||
DmStandardizedBatchExecutor batchExecutor,
|
||||
@Qualifier("dmStandardizedWriterExecutor") Executor writerExecutor) {
|
||||
@Qualifier("dmStandardizedWriterExecutor") Executor writerExecutor,
|
||||
DmLargeTextLimiter largeTextLimiter) {
|
||||
this.normalDataService = normalDataService;
|
||||
this.batchExecutor = batchExecutor;
|
||||
this.writerExecutor = writerExecutor;
|
||||
this.largeTextLimiter = largeTextLimiter;
|
||||
}
|
||||
|
||||
/** 保留已有单元测试和离线工具入口,默认不改变历史存储内容。 */
|
||||
public DmStandardizedBatchWriter(SyslogNormalDataService normalDataService,
|
||||
DmStandardizedBatchExecutor batchExecutor,
|
||||
Executor writerExecutor) {
|
||||
this(normalDataService, batchExecutor, writerExecutor, DmLargeTextLimiter.unlimited());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -148,6 +162,7 @@ public class DmStandardizedBatchWriter {
|
||||
List<WriteRequest<T>> prepared = new ArrayList<>(requests.size());
|
||||
for (WriteRequest<T> request : requests) {
|
||||
try {
|
||||
largeTextLimiter.truncateNormalRow(request.getData());
|
||||
normalDataService.prepareForInsert(request.getData());
|
||||
prepared.add(request);
|
||||
} catch (RuntimeException invalidRow) {
|
||||
@@ -178,10 +193,25 @@ public class DmStandardizedBatchWriter {
|
||||
List<CompletableFuture<WriteReport<T>>> futures = new ArrayList<>(groups.size());
|
||||
try {
|
||||
for (Map.Entry<BatchKey, List<WriteRequest<T>>> entry : groups.entrySet()) {
|
||||
long queuedAt = System.nanoTime();
|
||||
String batchId = org.slf4j.MDC.get("syslogBatchId");
|
||||
futures.add(CompletableFuture.supplyAsync(() -> {
|
||||
String previous = org.slf4j.MDC.get("syslogBatchId");
|
||||
if (batchId != null) org.slf4j.MDC.put("syslogBatchId", batchId);
|
||||
else org.slf4j.MDC.remove("syslogBatchId");
|
||||
try {
|
||||
long queueMs = (System.nanoTime() - queuedAt) / 1_000_000L;
|
||||
if (slowQueueThresholdMs > 0 && queueMs >= slowQueueThresholdMs) {
|
||||
log.warn("[SLOW_DM_QUEUE] batchId={}, alarmTable={}, rows={}, queueMs={}",
|
||||
batchId, entry.getKey().alarmTable, entry.getValue().size(), queueMs);
|
||||
}
|
||||
WriteReport<T> groupReport = new WriteReport<>();
|
||||
writeGroup(entry.getKey(), entry.getValue(), groupReport, budget);
|
||||
return groupReport;
|
||||
} finally {
|
||||
if (previous == null) org.slf4j.MDC.remove("syslogBatchId");
|
||||
else org.slf4j.MDC.put("syslogBatchId", previous);
|
||||
}
|
||||
}, writerExecutor));
|
||||
}
|
||||
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package com.common.service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* JDBC参数内容大小估算,不是网络包、数据库页或REDO大小。
|
||||
* 只统计实际INSERT字段,调用位置在截断/字段准备之后、绑定/执行之前。
|
||||
* 不读取LOB或流,不序列化任意对象,不保留字段值,不创建大字符串的UTF-8副本。
|
||||
*/
|
||||
final class DmWriteSizeEstimate {
|
||||
private String status = "NOT_MEASURED";
|
||||
private long payloadBytes;
|
||||
private long maxRowBytes;
|
||||
private long maxFieldBytes;
|
||||
private String maxFieldName = "none";
|
||||
private long unmeasuredValues;
|
||||
private long elapsedMs;
|
||||
|
||||
void measure(List<Map<String, Object>> rows, List<DmPreparedBatchInserter.ColumnMetadata> columns) {
|
||||
long started = System.nanoTime();
|
||||
try {
|
||||
for (Map<String, Object> row : rows) {
|
||||
long rowBytes = 0L;
|
||||
for (DmPreparedBatchInserter.ColumnMetadata column : columns) {
|
||||
long bytes = valueBytes(row.get(column.name));
|
||||
if (bytes < 0L) {
|
||||
unmeasuredValues++;
|
||||
continue;
|
||||
}
|
||||
rowBytes += bytes;
|
||||
if (bytes > maxFieldBytes) {
|
||||
maxFieldBytes = bytes;
|
||||
maxFieldName = column.name;
|
||||
}
|
||||
}
|
||||
payloadBytes += rowBytes;
|
||||
maxRowBytes = Math.max(maxRowBytes, rowBytes);
|
||||
}
|
||||
status = unmeasuredValues == 0L ? "COMPLETE" : "PARTIAL";
|
||||
} catch (RuntimeException diagnosticFailure) {
|
||||
// 观测失败不能改变事实写入行为;不记录异常消息,避免携带字段内容。
|
||||
status = "FAILED";
|
||||
} finally {
|
||||
elapsedMs = (System.nanoTime() - started) / 1_000_000L;
|
||||
}
|
||||
}
|
||||
|
||||
static long valueBytes(Object value) {
|
||||
if (value == null) return 0L;
|
||||
if (value instanceof String) return utf8Length((String) value);
|
||||
if (value instanceof byte[]) return ((byte[]) value).length;
|
||||
// 只对已知标量计其文本表示,避免任意对象toString触发IO或泄漏内容。
|
||||
Class<?> type = value.getClass();
|
||||
if (type == Boolean.class || type == Character.class || type == Byte.class
|
||||
|| type == Short.class || type == Integer.class || type == Long.class
|
||||
|| type == Float.class || type == Double.class || type == BigDecimal.class
|
||||
|| type == BigInteger.class || type == LocalDate.class || type == LocalDateTime.class
|
||||
|| type == Timestamp.class || type == java.sql.Date.class || type == java.sql.Time.class) {
|
||||
return utf8Length(value.toString());
|
||||
}
|
||||
if (type == java.util.Date.class) {
|
||||
return utf8Length(new Timestamp(((java.util.Date) value).getTime()).toString());
|
||||
}
|
||||
return -1L;
|
||||
}
|
||||
|
||||
/** 与JDK8 String.getBytes(UTF_8)一致:有效代理对4字节,孤立代理字符替换为一个问号字节。 */
|
||||
static long utf8Length(String text) {
|
||||
long bytes = 0L;
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char ch = text.charAt(i);
|
||||
if (ch < 0x80) bytes++;
|
||||
else if (ch < 0x800) bytes += 2L;
|
||||
else if (Character.isHighSurrogate(ch) && i + 1 < text.length()
|
||||
&& Character.isLowSurrogate(text.charAt(i + 1))) {
|
||||
bytes += 4L;
|
||||
i++;
|
||||
} else if (Character.isSurrogate(ch)) bytes++;
|
||||
else bytes += 3L;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
long getPayloadBytes() { return payloadBytes; }
|
||||
long getMaxRowBytes() { return maxRowBytes; }
|
||||
long getMaxFieldBytes() { return maxFieldBytes; }
|
||||
String getMaxFieldName() { return maxFieldName; }
|
||||
long getUnmeasuredValues() { return unmeasuredValues; }
|
||||
String getStatus() { return status; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "sizeEstimateStatus=" + status
|
||||
+ ", estimatedPayloadBytes=" + payloadBytes
|
||||
+ ", maxRowEstimatedBytes=" + maxRowBytes
|
||||
+ ", maxFieldEstimatedBytes=" + maxFieldBytes
|
||||
+ ", maxFieldName=" + maxFieldName
|
||||
+ ", unmeasuredValues=" + unmeasuredValues
|
||||
+ ", sizeEstimateMs=" + elapsedMs;
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.Modules.NormalData.SyslogFailureRouter;
|
||||
import com.common.entity.IngressStatsEvent;
|
||||
import com.common.util.Sm4Util;
|
||||
import com.common.util.SyslogParser;
|
||||
import com.config.AppProperties;
|
||||
import com.influx.raw.ReceiveTimeParser;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.kafka.annotation.KafkaListener;
|
||||
import org.springframework.kafka.support.Acknowledgment;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/** 独立消费原始Topic,只维护接收时间;不执行规则、采样或事实表写入。 */
|
||||
@Component
|
||||
@Slf4j
|
||||
public class IngressStatsConsumer {
|
||||
private final IngressStatsProjectionWriter writer;
|
||||
private final SyslogFailureRouter failureRouter;
|
||||
private final AppProperties appProperties;
|
||||
private final AtomicLong batches = new AtomicLong();
|
||||
private final AtomicLong invalidAttempts = new AtomicLong();
|
||||
private final AtomicLong writeFailures = new AtomicLong();
|
||||
|
||||
@Value("${spring.kafka.consumer.group-id}") private String rawGroup;
|
||||
@Value("${syslog.large-listener.group-id:${spring.kafka.consumer.group-id}-large}")
|
||||
private String largeRawGroup;
|
||||
@Value("${stats.ingress-metadata.group-id:${spring.kafka.consumer.group-id}-ingress-v1}")
|
||||
private String group;
|
||||
@Value("${stats.ingress-metadata.large-group-id:${stats.ingress-metadata.group-id}-large}")
|
||||
private String largeGroup;
|
||||
|
||||
public IngressStatsConsumer(IngressStatsProjectionWriter writer,
|
||||
SyslogFailureRouter failureRouter, AppProperties appProperties) {
|
||||
this.writer = writer;
|
||||
this.failureRouter = failureRouter;
|
||||
this.appProperties = appProperties;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void validateGroups() {
|
||||
if (group == null || group.trim().isEmpty() || largeGroup == null || largeGroup.trim().isEmpty()
|
||||
|| group.equals(largeGroup) || group.equals(rawGroup) || group.equals(largeRawGroup)
|
||||
|| largeGroup.equals(rawGroup) || largeGroup.equals(largeRawGroup)) {
|
||||
throw new IllegalStateException("入口统计必须使用与主消费隔离的非空 Kafka group-id");
|
||||
}
|
||||
log.info("Ingress stats consumer ready: group={}, largeGroup={}, mode=INDEPENDENT_KAFKA_DIRECT_MERGE",
|
||||
group, largeGroup);
|
||||
}
|
||||
|
||||
@KafkaListener(id = "syslog-ingress-stats", groupId = "${stats.ingress-metadata.group-id}",
|
||||
topics = "${spring.kafka.consumer.topic}",
|
||||
autoStartup = "${stats.ingress-metadata.enabled:true}",
|
||||
containerFactory = "ingressStatsKafkaListenerContainerFactory")
|
||||
public void consume(List<ConsumerRecord<String, String>> records, Acknowledgment ack) {
|
||||
consumeBatch(records, ack, "RAW");
|
||||
}
|
||||
|
||||
@KafkaListener(id = "syslog-ingress-stats-large", groupId = "${stats.ingress-metadata.large-group-id}",
|
||||
topics = "${spring.kafka.consumer.large-topic}",
|
||||
autoStartup = "#{${stats.ingress-metadata.enabled:true} && ${syslog.large-listener.enabled:true}}",
|
||||
containerFactory = "largeIngressStatsKafkaListenerContainerFactory")
|
||||
public void consumeLarge(List<ConsumerRecord<String, String>> records, Acknowledgment ack) {
|
||||
consumeBatch(records, ack, "RAW_LARGE");
|
||||
}
|
||||
|
||||
private void consumeBatch(List<ConsumerRecord<String, String>> records, Acknowledgment ack, String lane) {
|
||||
long started = System.nanoTime();
|
||||
List<IngressStatsEvent> events = new ArrayList<>(records.size());
|
||||
int invalid = 0;
|
||||
String firstInvalid = null;
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
try {
|
||||
events.add(decode(record));
|
||||
} catch (RuntimeException malformed) {
|
||||
invalid++;
|
||||
if (firstInvalid == null) firstInvalid = record.topic() + "-" + record.partition()
|
||||
+ "@" + record.offset() + ":" + malformed.getClass().getSimpleName();
|
||||
}
|
||||
}
|
||||
if (invalid > 0) {
|
||||
invalidAttempts.addAndGet(invalid);
|
||||
// 原始消息仍留在Kafka;坏头不会永久挡住其它设备接收状态,也不向业务Retry重复投递。
|
||||
log.error("[INGRESS_STATS_INVALID] lane={}, invalidRecords={}, firstInvalid={}, "
|
||||
+ "action=SKIP_INVALID_METADATA", lane, invalid, firstInvalid);
|
||||
}
|
||||
int groups;
|
||||
try {
|
||||
groups = writer.writeBatch(events);
|
||||
} catch (RuntimeException failure) {
|
||||
writeFailures.incrementAndGet();
|
||||
log.error("[INGRESS_STATS_WRITE_FAILED] lane={}, records={}, action=RETRY_STATS_GROUP",
|
||||
lane, records.size(), failure);
|
||||
throw failure;
|
||||
}
|
||||
// MIN/MAX更新和达梦提交均已完成,才推进独立统计组;重复消费不重复增加事实数量。
|
||||
ack.acknowledge();
|
||||
batches.incrementAndGet();
|
||||
log.info("[INGRESS_STATS_BATCH] lane={}, records={}, valid={}, invalid={}, groups={}, totalMs={}",
|
||||
lane, records.size(), events.size(), invalid, groups, (System.nanoTime() - started) / 1_000_000L);
|
||||
}
|
||||
|
||||
IngressStatsEvent decode(ConsumerRecord<String, String> record) {
|
||||
SyslogFailureRouter.MessageContext context = failureRouter.resolve(record);
|
||||
String decrypted = Sm4Util.decryptCbc(context.getPayload(), appProperties.getSm4Key());
|
||||
if (decrypted.indexOf(']') < 0) throw new IllegalArgumentException("缺少设备元数据头");
|
||||
Map<String, String> header = SyslogParser.parseKeyValuePairs(
|
||||
SyslogParser.substringBeforeFirstChar(decrypted, ']'));
|
||||
Long device = positiveId(header.get("device_id"));
|
||||
Long collector = positiveId(header.get("device_collect_id"));
|
||||
if (device == null && collector == null) throw new IllegalArgumentException("缺少有效设备/采集任务ID");
|
||||
return new IngressStatsEvent(context.getEventId(), device, collector,
|
||||
ReceiveTimeParser.parse(header.get("receive_time")).getLocalDateTime());
|
||||
}
|
||||
|
||||
private static Long positiveId(String value) {
|
||||
if (value == null || value.trim().isEmpty()) return null;
|
||||
long parsed = Long.parseLong(value);
|
||||
return parsed > 0L ? parsed : null;
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("group_id", group);
|
||||
result.put("large_group_id", largeGroup);
|
||||
result.put("successful_batches", batches.get());
|
||||
result.put("invalid_record_attempts", invalidAttempts.get());
|
||||
result.put("write_failures", writeFailures.get());
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+1
@@ -92,6 +92,7 @@ public class IngressStatsProjectionWriter {
|
||||
? "device_daily_stats+" + shadowDeviceTable : "device_daily_stats");
|
||||
status.put("business_materialization_mode", asynchronousMaterialization()
|
||||
? "KAFKA_DIRTY_KEY" : "SYNCHRONOUS");
|
||||
status.put("daily_projection_write_mode", "INDEPENDENT_KAFKA_DIRECT_MERGE");
|
||||
status.put("successful_batches", successfulBatches.get());
|
||||
status.put("received_events", receivedEvents.get());
|
||||
status.put("updated_groups", updatedGroups.get());
|
||||
|
||||
+51
-7
@@ -3,7 +3,8 @@ package com.common.service;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.TreeSet;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -12,11 +13,15 @@ import java.util.UUID;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
/**
|
||||
* 在标准化告警事实事务内登记事件时间桶。
|
||||
* 告警提交后登记事件时间桶,后台独立事务失败只重试通知,不回滚告警。
|
||||
*
|
||||
* <p>该通知不是“告警一定迟到”的结论。通知与事实在同一事务提交;下游能领取通知时,事实必然
|
||||
* <p>该通知不是“告警一定迟到”的结论。事实提交后才入队;下游能领取通知时,事实必然
|
||||
* 已经可见,再根据领取时已经完成的规则窗口决定是否重放。这里刻意不使用事实的
|
||||
* {@code created_at} 判断提交先后,因为 Kafka 积压时接收时间可能早于实际入库时间。
|
||||
*/
|
||||
@@ -38,12 +43,22 @@ public class LateAlarmBucketWriter {
|
||||
+ "VALUES (?,?,?,?,SYSDATE,1,0,0,'PENDING',0,0,SYSDATE,SYSDATE)";
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private final BestEffortAuxiliaryQueue queue = new BestEffortAuxiliaryQueue("LATE_ALARM_BUCKET", 256, 50000, true);
|
||||
|
||||
@Value("${analysis.late-replay.notify-timeout-seconds:5}")
|
||||
private int transactionTimeoutSeconds = 5;
|
||||
|
||||
@javax.annotation.PostConstruct public void start() { queue.start(); }
|
||||
@javax.annotation.PreDestroy public void stop() { queue.stop(); }
|
||||
public Map<String, Object> status() { return queue.status(); }
|
||||
|
||||
@Value("${analysis.late-replay.outbox-enabled:true}")
|
||||
private boolean enabled;
|
||||
|
||||
public LateAlarmBucketWriter(JdbcTemplate jdbcTemplate) {
|
||||
public LateAlarmBucketWriter(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.transactionManager = transactionManager;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,7 +71,27 @@ public class LateAlarmBucketWriter {
|
||||
return;
|
||||
}
|
||||
|
||||
Set<BucketKey> buckets = new LinkedHashSet<>();
|
||||
try {
|
||||
// 只保留设备/分钟的小键,不把原始日志和事实行滞留在后台队列。
|
||||
Set<BucketKey> buckets = buckets(rows);
|
||||
if (!TransactionSynchronizationManager.isActualTransactionActive()
|
||||
|| !TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
throw new IllegalStateException("迟到告警通知必须在事实提交后入队");
|
||||
}
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override public void afterCommit() {
|
||||
queue.offer(buckets.size(), () -> writeBuckets(buckets));
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException failure) {
|
||||
queue.loss("PREPARE_OR_REGISTER_FAILED", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<BucketKey> buckets(List<Map<String, Object>> rows) {
|
||||
// 不同Kafka批次可能含有相反顺序的设备/分钟,统一加锁顺序避免交叉等待。
|
||||
Set<BucketKey> buckets = new TreeSet<>(Comparator
|
||||
.comparing((BucketKey key) -> key.deviceId).thenComparing(key -> key.bucketStart));
|
||||
for (Map<String, Object> row : rows) {
|
||||
Integer deviceId = integerValue(row.get("device_id"));
|
||||
LocalDateTime eventTime = timeValue(row.get("log_time"));
|
||||
@@ -65,7 +100,14 @@ public class LateAlarmBucketWriter {
|
||||
}
|
||||
buckets.add(new BucketKey(deviceId, eventTime.truncatedTo(ChronoUnit.MINUTES)));
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
|
||||
private void writeBuckets(Set<BucketKey> buckets) {
|
||||
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
|
||||
transaction.setPropagationBehavior(org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
transaction.setTimeout(Math.max(1, transactionTimeoutSeconds));
|
||||
transaction.execute(status -> {
|
||||
for (BucketKey key : buckets) {
|
||||
LocalDateTime bucketEnd = key.bucketStart.plusMinutes(1);
|
||||
try {
|
||||
@@ -79,14 +121,16 @@ public class LateAlarmBucketWriter {
|
||||
Timestamp.valueOf(bucketEnd));
|
||||
} catch (RuntimeException failure) {
|
||||
// 多个 Kafka 分区可能同时首次写同一设备分钟,MERGE 的并发插入会竞争唯一键。
|
||||
// 交给外层事实事务整体回滚并有限重试,不能只吞掉 outbox 失败。
|
||||
// 仅后台通知事务回滚重试,绝不返回事实事务。
|
||||
if (isConcurrentWrite(failure)) {
|
||||
throw new DirectStatsProjectionWriter.ConcurrentStatsWriteException(
|
||||
"迟到告警分钟桶并发写入失败,可安全回滚后有限重试", failure);
|
||||
"迟到告警分钟桶并发写入失败,仅后台通知事务回滚重试", failure);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private Integer integerValue(Object value) {
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
import com.common.util.Utf8TextTruncator;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/** 普通来源消息完成规则和采样后,限制非告警达梦输出文本;调用方排除告警,不修改规则输入和InfluxDB原文。 */
|
||||
@Component
|
||||
public class RawLaneFieldLimiter {
|
||||
// 这些字段参与幂等、路由、分区或关联,不允许截断改变其语义。
|
||||
private static final Set<String> IDENTITY_FIELDS = new HashSet<>(Arrays.asList(
|
||||
"id", "syslog_uuid", "syslog_topic", "normalize_rule_id", "rule_version",
|
||||
"device_id", "tenant_id", "agent_id", "origin_agent_id", "collect_task_id",
|
||||
"log_time", "created_at", "receive_time", "event_level"));
|
||||
|
||||
private final long maxBytes;
|
||||
private final String rawTopic;
|
||||
|
||||
public RawLaneFieldLimiter(
|
||||
@Value("${syslog.raw-listener.field-max-utf8-bytes:2048}") long maxBytes,
|
||||
@Value("${spring.kafka.consumer.topic}") String rawTopic) {
|
||||
if (maxBytes < 0 || (maxBytes > 0 && maxBytes < 64)) {
|
||||
throw new IllegalArgumentException("syslog.raw-listener.field-max-utf8-bytes 必须为0或至少64");
|
||||
}
|
||||
this.maxBytes = maxBytes;
|
||||
this.rawTopic = rawTopic;
|
||||
}
|
||||
|
||||
public boolean appliesTo(String currentTopic, String originalTopic) {
|
||||
String sourceTopic = originalTopic == null || originalTopic.isEmpty() ? currentTopic : originalTopic;
|
||||
return maxBytes > 0 && rawTopic != null && rawTopic.equals(sourceTopic);
|
||||
}
|
||||
|
||||
/** 包括自定义映射文本,不限于旧的大字段白名单;数值、日期、二进制值保持原类型。 */
|
||||
public void truncateRow(Map<String, Object> row) {
|
||||
if (row == null || maxBytes == 0) return;
|
||||
for (Map.Entry<String, Object> entry : row.entrySet()) {
|
||||
if (entry.getValue() instanceof String && !IDENTITY_FIELDS.contains(entry.getKey())) {
|
||||
entry.setValue(truncate((String) entry.getValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void truncateNonNormal(SyslogNonNormalMessage message) {
|
||||
if (message == null || maxBytes == 0) return;
|
||||
message.setSyslogMessage(truncate(message.getSyslogMessage()));
|
||||
message.setHeaderMessage(truncate(message.getHeaderMessage()));
|
||||
message.setReasonDetail(truncate(message.getReasonDetail()));
|
||||
}
|
||||
|
||||
private String truncate(String value) {
|
||||
// 每个UTF-16代码单元最多占3个UTF-8字节,短字段无需分配UTF-8数组。
|
||||
if (value == null || (long) value.length() * 3L <= maxBytes) return value;
|
||||
return Utf8TextTruncator.truncate(value, maxBytes).getValue();
|
||||
}
|
||||
}
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/** Redis只保存每个消费实例的有界候选集,用于多实例汇聚,不承载逐条日志流。 */
|
||||
@Slf4j
|
||||
@Component
|
||||
public class RawLogCaptureClusterStore {
|
||||
private static final String PREFIX = "hb:xdr:raw-capture:";
|
||||
private static final String ACTIVE_KEY = PREFIX + "active";
|
||||
private static final TypeReference<Map<String, Object>> MAP_TYPE =
|
||||
new TypeReference<Map<String, Object>>() { };
|
||||
|
||||
private final StringRedisTemplate redis;
|
||||
private final ObjectMapper mapper;
|
||||
private final String nodeId;
|
||||
private final AtomicLong lastFailureLogAt = new AtomicLong();
|
||||
|
||||
@Value("${syslog.raw-capture.cluster-activation-delay-ms:1000}")
|
||||
private long activationDelayMs = 1000L;
|
||||
|
||||
public RawLogCaptureClusterStore(StringRedisTemplate redis,
|
||||
@Qualifier("httpObjectMapper") ObjectMapper mapper,
|
||||
@Value("${syslog.raw-capture.node-id:${HOSTNAME:unknown}}")
|
||||
String configuredNodeId) {
|
||||
this.redis = redis;
|
||||
this.mapper = mapper;
|
||||
this.nodeId = "unknown".equals(configuredNodeId)
|
||||
? UUID.randomUUID().toString() : configuredNodeId;
|
||||
}
|
||||
|
||||
Definition create(long deviceId, int durationSeconds, int settleSeconds, int messageCount,
|
||||
int maxActiveSessions, int retentionMinutes) {
|
||||
try {
|
||||
long now = System.currentTimeMillis();
|
||||
redis.opsForZSet().removeRangeByScore(ACTIVE_KEY, 0D, now - 1D);
|
||||
Long active = redis.opsForZSet().zCard(ACTIVE_KEY);
|
||||
if (active != null && active >= maxActiveSessions) {
|
||||
throw new RawLogCaptureService.CaptureCapacityException(maxActiveSessions);
|
||||
}
|
||||
long startedAt = now + Math.max(200L, activationDelayMs);
|
||||
Definition definition = new Definition(UUID.randomUUID().toString(), deviceId,
|
||||
startedAt, startedAt + durationSeconds * 1000L,
|
||||
startedAt + (durationSeconds + settleSeconds) * 1000L, messageCount,
|
||||
retentionMinutes);
|
||||
String metaKey = metaKey(definition.id);
|
||||
redis.opsForHash().putAll(metaKey, definition.toHash());
|
||||
redis.expire(metaKey, definition.ttlSeconds(now), TimeUnit.SECONDS);
|
||||
redis.opsForZSet().add(ACTIVE_KEY, definition.id, definition.settleEndsAt);
|
||||
return definition;
|
||||
} catch (RawLogCaptureService.CaptureCapacityException failure) {
|
||||
throw failure;
|
||||
} catch (RuntimeException failure) {
|
||||
throw new RawLogCaptureService.CaptureCoordinationException(failure);
|
||||
}
|
||||
}
|
||||
|
||||
List<Definition> active(long now) {
|
||||
redis.opsForZSet().removeRangeByScore(ACTIVE_KEY, 0D, now - 1D);
|
||||
Set<String> ids = redis.opsForZSet().rangeByScore(ACTIVE_KEY, now, Double.MAX_VALUE);
|
||||
if (ids == null || ids.isEmpty()) return Collections.emptyList();
|
||||
List<Definition> result = new ArrayList<>(ids.size());
|
||||
for (String id : ids) {
|
||||
Definition definition = definition(id);
|
||||
if (definition != null && definition.stoppedAt == 0L) result.add(definition);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void publish(RawLogCaptureService.CaptureCandidates candidates) {
|
||||
try {
|
||||
Definition definition = definition(candidates.getSessionId());
|
||||
if (definition == null || definition.stoppedAt > 0L) return;
|
||||
String snapshotKey = snapshotKey(candidates.getSessionId(), nodeId);
|
||||
redis.opsForValue().set(snapshotKey, mapper.writeValueAsString(toMap(candidates)),
|
||||
definition.ttlSeconds(System.currentTimeMillis()), TimeUnit.SECONDS);
|
||||
String nodesKey = nodesKey(candidates.getSessionId());
|
||||
redis.opsForSet().add(nodesKey, nodeId);
|
||||
redis.expire(nodesKey, definition.ttlSeconds(System.currentTimeMillis()), TimeUnit.SECONDS);
|
||||
} catch (Exception failure) {
|
||||
throw new RawLogCaptureService.CaptureCoordinationException(failure);
|
||||
}
|
||||
}
|
||||
|
||||
RawLogCaptureService.CaptureSnapshot get(String sessionId) {
|
||||
try {
|
||||
Definition definition = definition(sessionId);
|
||||
if (definition == null) return null;
|
||||
Set<String> nodes = redis.opsForSet().members(nodesKey(sessionId));
|
||||
List<RawLogCaptureService.CapturedLogSnapshot> first = new ArrayList<>();
|
||||
List<RawLogCaptureService.CapturedLogSnapshot> anomalies = new ArrayList<>();
|
||||
long received = 0L, processed = 0L, observedAnomalies = 0L;
|
||||
if (nodes != null) {
|
||||
for (String node : nodes) {
|
||||
String json = redis.opsForValue().get(snapshotKey(sessionId, node));
|
||||
if (json == null) continue;
|
||||
Map<String, Object> candidate = mapper.readValue(json, MAP_TYPE);
|
||||
received += longValue(candidate.get("receivedCount"));
|
||||
processed += longValue(candidate.get("processedCount"));
|
||||
observedAnomalies += longValue(candidate.get("observedAnomalyCount"));
|
||||
first.addAll(messages(candidate.get("firstMessages")));
|
||||
anomalies.addAll(messages(candidate.get("firstAnomalies")));
|
||||
}
|
||||
}
|
||||
List<RawLogCaptureService.CapturedLogSnapshot> selected =
|
||||
RawLogCaptureService.mergeCandidates(first, anomalies, definition.messageCount);
|
||||
int retainedAnomalies = 0;
|
||||
for (RawLogCaptureService.CapturedLogSnapshot message : selected) {
|
||||
if (message.isAnomaly()) retainedAnomalies++;
|
||||
}
|
||||
long replacements = replacementCount(first, anomalies, definition.messageCount);
|
||||
long now = System.currentTimeMillis();
|
||||
return new RawLogCaptureService.CaptureSnapshot(definition.id, definition.deviceId,
|
||||
definition.status(now), RawLogCaptureService.instant(definition.startedAt),
|
||||
RawLogCaptureService.instant(definition.captureEndsAt),
|
||||
RawLogCaptureService.instant(definition.settleEndsAt), definition.messageCount,
|
||||
received, processed, observedAnomalies, retainedAnomalies, replacements, selected);
|
||||
} catch (RawLogCaptureService.CaptureCoordinationException failure) {
|
||||
throw failure;
|
||||
} catch (Exception failure) {
|
||||
throw new RawLogCaptureService.CaptureCoordinationException(failure);
|
||||
}
|
||||
}
|
||||
|
||||
RawLogCaptureService.CaptureSnapshot stop(String sessionId) {
|
||||
try {
|
||||
Definition definition = definition(sessionId);
|
||||
if (definition == null) return null;
|
||||
redis.opsForHash().put(metaKey(sessionId), "stoppedAt",
|
||||
String.valueOf(System.currentTimeMillis()));
|
||||
redis.opsForZSet().remove(ACTIVE_KEY, sessionId);
|
||||
return get(sessionId);
|
||||
} catch (RawLogCaptureService.CaptureCoordinationException failure) {
|
||||
throw failure;
|
||||
} catch (RuntimeException failure) {
|
||||
throw new RawLogCaptureService.CaptureCoordinationException(failure);
|
||||
}
|
||||
}
|
||||
|
||||
void recordSyncFailure(RuntimeException failure) {
|
||||
long now = System.currentTimeMillis(), previous = lastFailureLogAt.get();
|
||||
if (now - previous >= 30_000L && lastFailureLogAt.compareAndSet(previous, now)) {
|
||||
log.warn("原始日志采样跨实例同步失败;不影响主消费链路: {}", failure.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private Definition definition(String id) {
|
||||
Map<Object, Object> values = redis.opsForHash().entries(metaKey(id));
|
||||
return values == null || values.isEmpty() ? null : Definition.from(id, values);
|
||||
}
|
||||
|
||||
private Map<String, Object> toMap(RawLogCaptureService.CaptureCandidates candidates) {
|
||||
Map<String, Object> value = new LinkedHashMap<>();
|
||||
value.put("receivedCount", candidates.getReceivedCount());
|
||||
value.put("processedCount", candidates.getProcessedCount());
|
||||
value.put("observedAnomalyCount", candidates.getObservedAnomalyCount());
|
||||
value.put("firstMessages", candidates.getFirstMessages());
|
||||
value.put("firstAnomalies", candidates.getFirstAnomalies());
|
||||
return value;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<RawLogCaptureService.CapturedLogSnapshot> messages(Object value) {
|
||||
if (!(value instanceof List)) return Collections.emptyList();
|
||||
List<RawLogCaptureService.CapturedLogSnapshot> result = new ArrayList<>();
|
||||
for (Object item : (List<?>) value) {
|
||||
if (!(item instanceof Map)) continue;
|
||||
Map<String, Object> map = (Map<String, Object>) item;
|
||||
Object receivedAt = map.get("receivedAt");
|
||||
result.add(new RawLogCaptureService.CapturedLogSnapshot(
|
||||
longValue(map.get("sequence")), string(map.get("eventId")),
|
||||
nullableLong(map.get("deviceId")), nullableLong(map.get("deviceCollectId")),
|
||||
string(map.get("topic")), localDateTime(receivedAt), string(map.get("observedAt")),
|
||||
string(map.get("processingStatus")), booleanValue(map.get("anomaly")),
|
||||
string(map.get("reason")), string(map.get("reasonDetail")),
|
||||
string(map.get("processedAt")), string(map.get("rawMessage"))));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private long replacementCount(List<RawLogCaptureService.CapturedLogSnapshot> first,
|
||||
List<RawLogCaptureService.CapturedLogSnapshot> anomalies, int limit) {
|
||||
int finalAnomalies = 0, initialAnomalies = 0;
|
||||
for (RawLogCaptureService.CapturedLogSnapshot value
|
||||
: RawLogCaptureService.mergeCandidates(first, anomalies, limit)) {
|
||||
if (value.isAnomaly()) finalAnomalies++;
|
||||
}
|
||||
List<RawLogCaptureService.CapturedLogSnapshot> initial =
|
||||
RawLogCaptureService.mergeCandidates(first, Collections.emptyList(), limit);
|
||||
for (RawLogCaptureService.CapturedLogSnapshot value : initial) {
|
||||
if (value.isAnomaly()) initialAnomalies++;
|
||||
}
|
||||
return Math.max(0, finalAnomalies - initialAnomalies);
|
||||
}
|
||||
|
||||
private static String metaKey(String id) { return PREFIX + "{" + id + "}:meta"; }
|
||||
private static String nodesKey(String id) { return PREFIX + "{" + id + "}:nodes"; }
|
||||
private static String snapshotKey(String id, String node) {
|
||||
return PREFIX + "{" + id + "}:node:" + node;
|
||||
}
|
||||
private static String string(Object value) { return value == null ? null : String.valueOf(value); }
|
||||
private static long longValue(Object value) {
|
||||
return value == null ? 0L : Long.parseLong(String.valueOf(value));
|
||||
}
|
||||
private static Long nullableLong(Object value) {
|
||||
return value == null ? null : Long.valueOf(String.valueOf(value));
|
||||
}
|
||||
private static boolean booleanValue(Object value) {
|
||||
return value != null && Boolean.parseBoolean(String.valueOf(value));
|
||||
}
|
||||
private static LocalDateTime localDateTime(Object value) {
|
||||
if (value == null) return null;
|
||||
if (value instanceof List) {
|
||||
List<?> parts = (List<?>) value;
|
||||
if (parts.size() >= 6) {
|
||||
int nano = parts.size() >= 7 ? ((Number) parts.get(6)).intValue() : 0;
|
||||
return LocalDateTime.of(((Number) parts.get(0)).intValue(),
|
||||
((Number) parts.get(1)).intValue(), ((Number) parts.get(2)).intValue(),
|
||||
((Number) parts.get(3)).intValue(), ((Number) parts.get(4)).intValue(),
|
||||
((Number) parts.get(5)).intValue(), nano);
|
||||
}
|
||||
}
|
||||
return LocalDateTime.parse(String.valueOf(value));
|
||||
}
|
||||
|
||||
static final class Definition {
|
||||
private final String id;
|
||||
private final long deviceId;
|
||||
private final long startedAt;
|
||||
private final long captureEndsAt;
|
||||
private final long settleEndsAt;
|
||||
private final int messageCount;
|
||||
private final int retentionMinutes;
|
||||
private final long stoppedAt;
|
||||
|
||||
Definition(String id, long deviceId, long startedAt, long captureEndsAt,
|
||||
long settleEndsAt, int messageCount, int retentionMinutes) {
|
||||
this(id, deviceId, startedAt, captureEndsAt, settleEndsAt, messageCount,
|
||||
retentionMinutes, 0L);
|
||||
}
|
||||
|
||||
private Definition(String id, long deviceId, long startedAt, long captureEndsAt,
|
||||
long settleEndsAt, int messageCount, int retentionMinutes,
|
||||
long stoppedAt) {
|
||||
this.id = id; this.deviceId = deviceId; this.startedAt = startedAt;
|
||||
this.captureEndsAt = captureEndsAt; this.settleEndsAt = settleEndsAt;
|
||||
this.messageCount = messageCount; this.retentionMinutes = retentionMinutes;
|
||||
this.stoppedAt = stoppedAt;
|
||||
}
|
||||
|
||||
private Map<String, String> toHash() {
|
||||
Map<String, String> value = new LinkedHashMap<>();
|
||||
value.put("deviceId", String.valueOf(deviceId));
|
||||
value.put("startedAt", String.valueOf(startedAt));
|
||||
value.put("captureEndsAt", String.valueOf(captureEndsAt));
|
||||
value.put("settleEndsAt", String.valueOf(settleEndsAt));
|
||||
value.put("messageCount", String.valueOf(messageCount));
|
||||
value.put("retentionMinutes", String.valueOf(retentionMinutes));
|
||||
value.put("stoppedAt", String.valueOf(stoppedAt));
|
||||
return value;
|
||||
}
|
||||
|
||||
private static Definition from(String id, Map<Object, Object> map) {
|
||||
return new Definition(id, longValue(map.get("deviceId")), longValue(map.get("startedAt")),
|
||||
longValue(map.get("captureEndsAt")), longValue(map.get("settleEndsAt")),
|
||||
(int) longValue(map.get("messageCount")),
|
||||
(int) longValue(map.get("retentionMinutes")), longValue(map.get("stoppedAt")));
|
||||
}
|
||||
|
||||
private long ttlSeconds(long now) {
|
||||
long remainingMillis = Math.max(0L, settleEndsAt - now);
|
||||
return Math.max(60L, (remainingMillis + 999L) / 1000L
|
||||
+ retentionMinutes * 60L);
|
||||
}
|
||||
private String status(long now) {
|
||||
if (stoppedAt > 0L) return "CANCELLED";
|
||||
if (now < startedAt) return "SCHEDULED";
|
||||
if (now <= captureEndsAt) return "RUNNING";
|
||||
if (now <= settleEndsAt) return "DRAINING";
|
||||
return "COMPLETED";
|
||||
}
|
||||
String getId() { return id; }
|
||||
long getDeviceId() { return deviceId; }
|
||||
long getStartedAt() { return startedAt; }
|
||||
long getCaptureEndsAt() { return captureEndsAt; }
|
||||
long getSettleEndsAt() { return settleEndsAt; }
|
||||
int getMessageCount() { return messageCount; }
|
||||
}
|
||||
}
|
||||
+798
@@ -0,0 +1,798 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.Modules.NormalData.LogNormalProcessor;
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
* 面向现场诊断的有界原始日志采样器。
|
||||
*
|
||||
* <p>普通消息按到达顺序填充固定容量;容量满后,新的异常消息会淘汰最早的非异常消息。
|
||||
* 异常消息之间仍保持先到先得,避免高流量设备导致内存随消息数增长。</p>
|
||||
*/
|
||||
@Service
|
||||
public class RawLogCaptureService {
|
||||
|
||||
public static final int MAX_DURATION_SECONDS = 600;
|
||||
public static final int MAX_MESSAGE_COUNT = 50;
|
||||
|
||||
@Value("${syslog.raw-capture.enabled:true}")
|
||||
private boolean enabled = true;
|
||||
|
||||
@Value("${syslog.raw-capture.max-active-sessions:20}")
|
||||
private int maxActiveSessions = 20;
|
||||
|
||||
@Value("${syslog.raw-capture.max-retained-sessions:100}")
|
||||
private int maxRetainedSessions = 100;
|
||||
|
||||
@Value("${syslog.raw-capture.settle-seconds:30}")
|
||||
private int settleSeconds = 30;
|
||||
|
||||
@Value("${syslog.raw-capture.result-retention-minutes:30}")
|
||||
private int resultRetentionMinutes = 30;
|
||||
|
||||
private final Clock clock;
|
||||
private final ConcurrentHashMap<String, CaptureSession> sessions = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<Long, CopyOnWriteArrayList<CaptureSession>> sessionsByDevice =
|
||||
new ConcurrentHashMap<>();
|
||||
private final AtomicLong sequence = new AtomicLong();
|
||||
|
||||
/** 跨实例同步由独立存储组件完成;单元测试或明确关闭时退化为单实例模式。 */
|
||||
@Autowired(required = false)
|
||||
private RawLogCaptureClusterStore clusterStore;
|
||||
|
||||
@Value("${syslog.raw-capture.cluster-enabled:true}")
|
||||
private boolean clusterEnabled = true;
|
||||
|
||||
public RawLogCaptureService() {
|
||||
this(Clock.systemUTC());
|
||||
}
|
||||
|
||||
RawLogCaptureService(Clock clock) {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void validateConfiguration() {
|
||||
if (maxActiveSessions < 1 || maxActiveSessions > 1000) {
|
||||
throw new IllegalArgumentException("syslog.raw-capture.max-active-sessions 必须在 1~1000 之间");
|
||||
}
|
||||
if (maxRetainedSessions < maxActiveSessions || maxRetainedSessions > 5000) {
|
||||
throw new IllegalArgumentException(
|
||||
"syslog.raw-capture.max-retained-sessions 必须不小于活动会话上限且不超过 5000");
|
||||
}
|
||||
if (settleSeconds < 0 || settleSeconds > 300) {
|
||||
throw new IllegalArgumentException("syslog.raw-capture.settle-seconds 必须在 0~300 之间");
|
||||
}
|
||||
if (resultRetentionMinutes < 1 || resultRetentionMinutes > 1440) {
|
||||
throw new IllegalArgumentException("syslog.raw-capture.result-retention-minutes 必须在 1~1440 之间");
|
||||
}
|
||||
}
|
||||
|
||||
public CaptureSnapshot start(long deviceId, int durationSeconds, int messageCount) {
|
||||
if (!enabled) throw new CaptureDisabledException();
|
||||
if (deviceId <= 0L) throw new IllegalArgumentException("deviceId 必须大于 0");
|
||||
if (durationSeconds < 1 || durationSeconds > MAX_DURATION_SECONDS) {
|
||||
throw new IllegalArgumentException("durationSeconds 必须在 1~600 之间");
|
||||
}
|
||||
if (messageCount < 1 || messageCount > MAX_MESSAGE_COUNT) {
|
||||
throw new IllegalArgumentException("messageCount 必须在 1~50 之间");
|
||||
}
|
||||
if (useClusterStore()) {
|
||||
RawLogCaptureClusterStore.Definition definition = clusterStore.create(deviceId,
|
||||
durationSeconds, settleSeconds, messageCount, maxActiveSessions,
|
||||
resultRetentionMinutes);
|
||||
ensureClusterSession(definition);
|
||||
return clusterStore.get(definition.getId());
|
||||
}
|
||||
cleanup(clock.millis());
|
||||
synchronized (this) {
|
||||
long startedAt = clock.millis();
|
||||
if (activeSessionCount(startedAt) >= maxActiveSessions) {
|
||||
throw new CaptureCapacityException(maxActiveSessions);
|
||||
}
|
||||
makeRoomForRetainedSession(startedAt);
|
||||
CaptureSession session = new CaptureSession(UUID.randomUUID().toString(), deviceId,
|
||||
startedAt, startedAt + durationSeconds * 1000L,
|
||||
startedAt + (durationSeconds + settleSeconds) * 1000L, messageCount);
|
||||
sessions.put(session.id, session);
|
||||
sessionsByDevice.computeIfAbsent(deviceId, ignored -> new CopyOnWriteArrayList<>())
|
||||
.add(session);
|
||||
return session.snapshot(startedAt);
|
||||
}
|
||||
}
|
||||
|
||||
public CaptureSnapshot get(String sessionId) {
|
||||
if (useClusterStore()) return clusterStore.get(sessionId);
|
||||
long now = clock.millis();
|
||||
cleanup(now);
|
||||
CaptureSession session = sessions.get(sessionId);
|
||||
return session == null ? null : session.snapshot(now);
|
||||
}
|
||||
|
||||
public CaptureSnapshot stop(String sessionId) {
|
||||
if (useClusterStore()) {
|
||||
CaptureSnapshot snapshot = clusterStore.stop(sessionId);
|
||||
CaptureSession local = sessions.get(sessionId);
|
||||
if (local != null) local.stop(clock.millis());
|
||||
if (local != null) removeFromActiveIndex(local);
|
||||
return snapshot;
|
||||
}
|
||||
long now = clock.millis();
|
||||
CaptureSession session = sessions.get(sessionId);
|
||||
if (session == null) return null;
|
||||
session.stop(now);
|
||||
removeFromActiveIndex(session);
|
||||
return session.snapshot(now);
|
||||
}
|
||||
|
||||
/** 在解密并识别设备后调用;只保存固定容量的最早样本。 */
|
||||
public void observeReceived(long observedAtEpochMillis, Long deviceId, Long deviceCollectId,
|
||||
String eventId, String topic, LocalDateTime receivedAt,
|
||||
String rawMessage) {
|
||||
if (!enabled || deviceId == null) return;
|
||||
List<CaptureSession> active = sessionsByDevice.get(deviceId);
|
||||
if (active == null || active.isEmpty()) return;
|
||||
ReceivedLog received = new ReceivedLog(orderSequence(observedAtEpochMillis), observedAtEpochMillis,
|
||||
deviceId, deviceCollectId, eventId, topic, receivedAt, rawMessage);
|
||||
for (CaptureSession session : active) session.received(received);
|
||||
}
|
||||
|
||||
/** 记录规则处理结果;非标结果具有异常优先级。 */
|
||||
public void observeNormalization(long observedAtEpochMillis, Long deviceId, Long deviceCollectId,
|
||||
String eventId, String topic, LocalDateTime receivedAt,
|
||||
String rawMessage,
|
||||
LogNormalProcessor.NormalizationResult result) {
|
||||
if (result == null) return;
|
||||
if (!result.getNonNormalMessages().isEmpty()) {
|
||||
SyslogNonNormalMessage first = result.getNonNormalMessages().get(0);
|
||||
observeOutcome(observedAtEpochMillis, deviceId, deviceCollectId, eventId, topic,
|
||||
receivedAt, rawMessage, "NON_NORMAL", true,
|
||||
first.getReason(), first.getReasonDetail());
|
||||
} else if (result.getOutcome() == LogNormalProcessor.ProcessingOutcome.FILTERED) {
|
||||
observeOutcome(observedAtEpochMillis, deviceId, deviceCollectId, eventId, topic,
|
||||
receivedAt, rawMessage, "FILTERED", false, "规则过滤", null);
|
||||
} else {
|
||||
observeOutcome(observedAtEpochMillis, deviceId, deviceCollectId, eventId, topic,
|
||||
receivedAt, rawMessage, "SUCCESS", false, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
/** 记录 Retry/DLT、规则执行或持久化异常;异常可替换已有普通样本。 */
|
||||
public void observeFailure(long observedAtEpochMillis, Long deviceId, Long deviceCollectId,
|
||||
String eventId, String topic, LocalDateTime receivedAt,
|
||||
String rawMessage, String stage, String terminalState,
|
||||
Throwable failure) {
|
||||
String status = terminalState == null || terminalState.trim().isEmpty()
|
||||
? "ERROR" : terminalState;
|
||||
String reason = stage == null || stage.trim().isEmpty() ? "处理异常" : stage;
|
||||
String detail = failure == null ? null : failure.getClass().getName()
|
||||
+ (failure.getMessage() == null ? "" : ": " + failure.getMessage());
|
||||
observeOutcome(observedAtEpochMillis, deviceId, deviceCollectId, eventId, topic,
|
||||
receivedAt, rawMessage, status, true, reason, abbreviate(detail, 2000));
|
||||
}
|
||||
|
||||
private void observeOutcome(long observedAtEpochMillis, Long deviceId, Long deviceCollectId,
|
||||
String eventId, String topic, LocalDateTime receivedAt,
|
||||
String rawMessage, String status, boolean anomaly,
|
||||
String reason, String detail) {
|
||||
if (!enabled || deviceId == null) return;
|
||||
List<CaptureSession> active = sessionsByDevice.get(deviceId);
|
||||
if (active == null || active.isEmpty()) return;
|
||||
ReceivedLog received = new ReceivedLog(orderSequence(observedAtEpochMillis), observedAtEpochMillis,
|
||||
deviceId, deviceCollectId, eventId, topic, receivedAt, rawMessage);
|
||||
long now = clock.millis();
|
||||
for (CaptureSession session : active) {
|
||||
session.outcome(received, status, anomaly, reason, detail, now);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 多实例每200ms同步一次会话定义和变化过的有界候选集;单实例降级模式用同一定时器
|
||||
* 主动清理过期结果。API创建时预留1秒激活时间,避免轮询传播丢掉窗口开头的日志。
|
||||
*/
|
||||
@Scheduled(fixedDelayString = "${syslog.raw-capture.cluster-sync-interval-ms:200}")
|
||||
public void synchronizeClusterSessions() {
|
||||
if (!enabled) return;
|
||||
if (!useClusterStore()) {
|
||||
cleanup(clock.millis());
|
||||
return;
|
||||
}
|
||||
try {
|
||||
long now = clock.millis();
|
||||
List<RawLogCaptureClusterStore.Definition> definitions = clusterStore.active(now);
|
||||
Map<String, Boolean> activeIds = new LinkedHashMap<>();
|
||||
for (RawLogCaptureClusterStore.Definition definition : definitions) {
|
||||
activeIds.put(definition.getId(), Boolean.TRUE);
|
||||
CaptureSession session = ensureClusterSession(definition);
|
||||
CaptureCandidates candidates = session.candidatesIfChanged();
|
||||
if (candidates != null) {
|
||||
clusterStore.publish(candidates);
|
||||
session.markPublished(candidates.getRevision());
|
||||
}
|
||||
}
|
||||
for (CaptureSession session : sessions.values()) {
|
||||
if (session.clusterSession && !activeIds.containsKey(session.id)) {
|
||||
clusterStore.publish(session.finalCandidates());
|
||||
session.stop(now);
|
||||
removeFromActiveIndex(session);
|
||||
sessions.remove(session.id, session);
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
clusterStore.recordSyncFailure(failure);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean useClusterStore() {
|
||||
return clusterEnabled && clusterStore != null;
|
||||
}
|
||||
|
||||
private CaptureSession ensureClusterSession(RawLogCaptureClusterStore.Definition definition) {
|
||||
CaptureSession existing = sessions.get(definition.getId());
|
||||
if (existing != null) return existing;
|
||||
CaptureSession created = new CaptureSession(definition.getId(), definition.getDeviceId(),
|
||||
definition.getStartedAt(), definition.getCaptureEndsAt(),
|
||||
definition.getSettleEndsAt(), definition.getMessageCount(), true);
|
||||
CaptureSession winner = sessions.putIfAbsent(created.id, created);
|
||||
CaptureSession session = winner == null ? created : winner;
|
||||
if (winner == null) {
|
||||
sessionsByDevice.computeIfAbsent(created.deviceId,
|
||||
ignored -> new CopyOnWriteArrayList<>()).add(created);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
private synchronized int activeSessionCount(long now) {
|
||||
int count = 0;
|
||||
for (CaptureSession session : sessions.values()) {
|
||||
if (session.isActive(now)) count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/** 总结果数满时优先淘汰最早完成的会话,活动会话绝不被淘汰。 */
|
||||
private void makeRoomForRetainedSession(long now) {
|
||||
while (sessions.size() >= maxRetainedSessions) {
|
||||
CaptureSession oldestFinished = null;
|
||||
for (CaptureSession session : sessions.values()) {
|
||||
if (session.isActive(now)) continue;
|
||||
if (oldestFinished == null || session.finishedAt() < oldestFinished.finishedAt()) {
|
||||
oldestFinished = session;
|
||||
}
|
||||
}
|
||||
if (oldestFinished == null) {
|
||||
throw new CaptureCapacityException(maxRetainedSessions);
|
||||
}
|
||||
sessions.remove(oldestFinished.id, oldestFinished);
|
||||
removeFromActiveIndex(oldestFinished);
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanup(long now) {
|
||||
for (CaptureSession session : sessions.values()) {
|
||||
if (!session.isActive(now)) removeFromActiveIndex(session);
|
||||
if (session.removableAt(resultRetentionMinutes) < now) sessions.remove(session.id, session);
|
||||
}
|
||||
}
|
||||
|
||||
private void removeFromActiveIndex(CaptureSession session) {
|
||||
CopyOnWriteArrayList<CaptureSession> active = sessionsByDevice.get(session.deviceId);
|
||||
if (active == null) return;
|
||||
active.remove(session);
|
||||
if (active.isEmpty()) sessionsByDevice.remove(session.deviceId, active);
|
||||
}
|
||||
|
||||
private static String abbreviate(String value, int maxChars) {
|
||||
if (value == null || value.length() <= maxChars) return value;
|
||||
return value.substring(0, maxChars) + "...[truncated]";
|
||||
}
|
||||
|
||||
static String instant(long epochMillis) {
|
||||
return Instant.ofEpochMilli(epochMillis).toString();
|
||||
}
|
||||
|
||||
private long orderSequence(long observedAtEpochMillis) {
|
||||
return observedAtEpochMillis * 1_000_000L + sequence.incrementAndGet() % 1_000_000L;
|
||||
}
|
||||
|
||||
static List<CapturedLogSnapshot> mergeCandidates(List<CapturedLogSnapshot> firstCandidates,
|
||||
List<CapturedLogSnapshot> anomalyCandidates,
|
||||
int limit) {
|
||||
Map<String, CapturedLogSnapshot> uniqueFirst = uniqueByEvent(firstCandidates);
|
||||
List<CapturedLogSnapshot> first = new ArrayList<>(uniqueFirst.values());
|
||||
first.sort(Comparator.comparingLong(CapturedLogSnapshot::getSequence));
|
||||
if (first.size() > limit) first = new ArrayList<>(first.subList(0, limit));
|
||||
|
||||
Map<String, CapturedLogSnapshot> uniqueAnomalies = uniqueByEvent(anomalyCandidates);
|
||||
List<CapturedLogSnapshot> anomalies = new ArrayList<>(uniqueAnomalies.values());
|
||||
anomalies.sort(Comparator.comparingLong(CapturedLogSnapshot::getSequence));
|
||||
if (anomalies.size() > limit) anomalies = anomalies.subList(0, limit);
|
||||
|
||||
Map<String, CapturedLogSnapshot> selected = uniqueByEvent(first);
|
||||
for (CapturedLogSnapshot anomaly : anomalies) {
|
||||
String key = eventKey(anomaly);
|
||||
if (selected.containsKey(key)) {
|
||||
selected.put(key, anomaly);
|
||||
continue;
|
||||
}
|
||||
if (selected.size() < limit) {
|
||||
selected.put(key, anomaly);
|
||||
continue;
|
||||
}
|
||||
String oldestNormal = null;
|
||||
long oldestSequence = Long.MAX_VALUE;
|
||||
for (Map.Entry<String, CapturedLogSnapshot> entry : selected.entrySet()) {
|
||||
CapturedLogSnapshot candidate = entry.getValue();
|
||||
if (!candidate.isAnomaly() && candidate.getSequence() < oldestSequence) {
|
||||
oldestNormal = entry.getKey();
|
||||
oldestSequence = candidate.getSequence();
|
||||
}
|
||||
}
|
||||
if (oldestNormal == null) break;
|
||||
selected.remove(oldestNormal);
|
||||
selected.put(key, anomaly);
|
||||
}
|
||||
List<CapturedLogSnapshot> result = new ArrayList<>(selected.values());
|
||||
result.sort(Comparator.comparingLong(CapturedLogSnapshot::getSequence));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Map<String, CapturedLogSnapshot> uniqueByEvent(
|
||||
List<CapturedLogSnapshot> candidates) {
|
||||
Map<String, CapturedLogSnapshot> result = new LinkedHashMap<>();
|
||||
if (candidates == null) return result;
|
||||
for (CapturedLogSnapshot candidate : candidates) {
|
||||
String key = eventKey(candidate);
|
||||
CapturedLogSnapshot existing = result.get(key);
|
||||
if (existing == null || (!existing.isAnomaly() && candidate.isAnomaly())) {
|
||||
result.put(key, candidate);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String eventKey(CapturedLogSnapshot candidate) {
|
||||
return candidate.getEventId() == null
|
||||
? "sequence:" + candidate.getSequence() : "event:" + candidate.getEventId();
|
||||
}
|
||||
|
||||
private static List<CapturedLogSnapshot> snapshots(List<CapturedLog> logs) {
|
||||
List<CapturedLogSnapshot> result = new ArrayList<>(logs.size());
|
||||
for (CapturedLog log : logs) result.add(log.snapshot());
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int countAnomalies(List<CapturedLogSnapshot> messages) {
|
||||
int count = 0;
|
||||
for (CapturedLogSnapshot message : messages) if (message.isAnomaly()) count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
private static long replacementCount(List<CapturedLogSnapshot> first,
|
||||
List<CapturedLogSnapshot> anomalies, int limit) {
|
||||
Map<String, CapturedLogSnapshot> firstSet = uniqueByEvent(first);
|
||||
int laterAnomalies = 0;
|
||||
for (CapturedLogSnapshot anomaly : uniqueByEvent(anomalies).values()) {
|
||||
if (!firstSet.containsKey(eventKey(anomaly))) laterAnomalies++;
|
||||
}
|
||||
int availableNormals = 0;
|
||||
List<CapturedLogSnapshot> globalFirst = new ArrayList<>(firstSet.values());
|
||||
globalFirst.sort(Comparator.comparingLong(CapturedLogSnapshot::getSequence));
|
||||
for (int i = 0; i < Math.min(limit, globalFirst.size()); i++) {
|
||||
if (!globalFirst.get(i).isAnomaly()) availableNormals++;
|
||||
}
|
||||
return Math.min(laterAnomalies, availableNormals);
|
||||
}
|
||||
|
||||
private static final class ReceivedLog {
|
||||
private final long sequence;
|
||||
private final long observedAt;
|
||||
private final Long deviceId;
|
||||
private final Long deviceCollectId;
|
||||
private final String eventId;
|
||||
private final String topic;
|
||||
private final LocalDateTime receivedAt;
|
||||
private final String rawMessage;
|
||||
|
||||
private ReceivedLog(long sequence, long observedAt, Long deviceId, Long deviceCollectId,
|
||||
String eventId, String topic, LocalDateTime receivedAt, String rawMessage) {
|
||||
this.sequence = sequence;
|
||||
this.observedAt = observedAt;
|
||||
this.deviceId = deviceId;
|
||||
this.deviceCollectId = deviceCollectId;
|
||||
this.eventId = eventId;
|
||||
this.topic = topic;
|
||||
this.receivedAt = receivedAt;
|
||||
this.rawMessage = rawMessage;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class CaptureSession {
|
||||
private final String id;
|
||||
private final long deviceId;
|
||||
private final long startedAt;
|
||||
private final long captureEndsAt;
|
||||
private final long settleEndsAt;
|
||||
private final int messageCount;
|
||||
private final List<CapturedLog> firstMessages = new ArrayList<>();
|
||||
private final List<CapturedLog> firstAnomalies = new ArrayList<>();
|
||||
private final Map<String, CapturedLog> firstByEventId = new LinkedHashMap<>();
|
||||
private final Map<String, CapturedLog> anomalyByEventId = new LinkedHashMap<>();
|
||||
private final boolean clusterSession;
|
||||
private long revision;
|
||||
private long publishedRevision = -1L;
|
||||
private long stoppedAt;
|
||||
private long receivedCount;
|
||||
private long processedCount;
|
||||
private long observedAnomalyCount;
|
||||
private long replacementCount;
|
||||
|
||||
private CaptureSession(String id, long deviceId, long startedAt, long captureEndsAt,
|
||||
long settleEndsAt, int messageCount) {
|
||||
this(id, deviceId, startedAt, captureEndsAt, settleEndsAt, messageCount, false);
|
||||
}
|
||||
|
||||
private CaptureSession(String id, long deviceId, long startedAt, long captureEndsAt,
|
||||
long settleEndsAt, int messageCount, boolean clusterSession) {
|
||||
this.id = id;
|
||||
this.deviceId = deviceId;
|
||||
this.startedAt = startedAt;
|
||||
this.captureEndsAt = captureEndsAt;
|
||||
this.settleEndsAt = settleEndsAt;
|
||||
this.messageCount = messageCount;
|
||||
this.clusterSession = clusterSession;
|
||||
}
|
||||
|
||||
private synchronized void received(ReceivedLog log) {
|
||||
if (!accepts(log.observedAt) || stoppedAt > 0L) return;
|
||||
receivedCount++;
|
||||
if (findFirst(log.eventId) != null || firstMessages.size() >= messageCount) return;
|
||||
CapturedLog captured = new CapturedLog(log);
|
||||
firstMessages.add(captured);
|
||||
if (captured.eventId != null) firstByEventId.put(captured.eventId, captured);
|
||||
revision++;
|
||||
}
|
||||
|
||||
private synchronized void outcome(ReceivedLog log, String status, boolean anomaly,
|
||||
String reason, String detail, long now) {
|
||||
if (!accepts(log.observedAt) || stoppedAt > 0L || now > settleEndsAt) return;
|
||||
processedCount++;
|
||||
if (anomaly) observedAnomalyCount++;
|
||||
CapturedLog first = findFirst(log.eventId);
|
||||
if (first != null) {
|
||||
first.update(status, anomaly, reason, detail, now);
|
||||
revision++;
|
||||
}
|
||||
CapturedLog existingAnomaly = findAnomaly(log.eventId);
|
||||
if (existingAnomaly != null) {
|
||||
existingAnomaly.update(status, anomaly, reason, detail, now);
|
||||
revision++;
|
||||
}
|
||||
if (!anomaly || existingAnomaly != null || firstAnomalies.size() >= messageCount) return;
|
||||
CapturedLog captured = first == null ? new CapturedLog(log) : first.copy();
|
||||
captured.update(status, true, reason, detail, now);
|
||||
firstAnomalies.add(captured);
|
||||
if (captured.eventId != null) anomalyByEventId.put(captured.eventId, captured);
|
||||
revision++;
|
||||
}
|
||||
|
||||
private boolean accepts(long observedAt) {
|
||||
return observedAt >= startedAt && observedAt <= captureEndsAt;
|
||||
}
|
||||
|
||||
private CapturedLog findFirst(String eventId) {
|
||||
return eventId == null ? null : firstByEventId.get(eventId);
|
||||
}
|
||||
|
||||
private CapturedLog findAnomaly(String eventId) {
|
||||
return eventId == null ? null : anomalyByEventId.get(eventId);
|
||||
}
|
||||
|
||||
private synchronized void stop(long now) {
|
||||
if (stoppedAt == 0L) stoppedAt = now;
|
||||
}
|
||||
|
||||
private synchronized boolean isActive(long now) {
|
||||
return stoppedAt == 0L && now <= settleEndsAt;
|
||||
}
|
||||
|
||||
private synchronized long removableAt(int retentionMinutes) {
|
||||
return finishedAt() + retentionMinutes * 60_000L;
|
||||
}
|
||||
|
||||
private synchronized long finishedAt() {
|
||||
return stoppedAt > 0L ? stoppedAt : settleEndsAt;
|
||||
}
|
||||
|
||||
private synchronized CaptureSnapshot snapshot(long now) {
|
||||
List<CapturedLogSnapshot> first = snapshots(firstMessages);
|
||||
List<CapturedLogSnapshot> anomalies = snapshots(firstAnomalies);
|
||||
List<CapturedLogSnapshot> logs = mergeCandidates(first, anomalies, messageCount);
|
||||
int retainedAnomalies = countAnomalies(logs);
|
||||
replacementCount = replacementCount(first, anomalies, messageCount);
|
||||
return new CaptureSnapshot(id, deviceId, status(now), instant(startedAt),
|
||||
instant(captureEndsAt), instant(settleEndsAt), messageCount,
|
||||
receivedCount, processedCount, observedAnomalyCount,
|
||||
retainedAnomalies, replacementCount, logs);
|
||||
}
|
||||
|
||||
private synchronized CaptureCandidates candidatesIfChanged() {
|
||||
if (!clusterSession || revision == publishedRevision) return null;
|
||||
return candidates();
|
||||
}
|
||||
|
||||
private synchronized CaptureCandidates finalCandidates() {
|
||||
return candidates();
|
||||
}
|
||||
|
||||
private CaptureCandidates candidates() {
|
||||
return new CaptureCandidates(id, deviceId, startedAt, captureEndsAt, settleEndsAt,
|
||||
messageCount, receivedCount, processedCount, observedAnomalyCount,
|
||||
snapshots(firstMessages), snapshots(firstAnomalies), revision);
|
||||
}
|
||||
|
||||
private synchronized void markPublished(long candidateRevision) {
|
||||
if (candidateRevision > publishedRevision) publishedRevision = candidateRevision;
|
||||
}
|
||||
|
||||
private String status(long now) {
|
||||
if (stoppedAt > 0L) return "CANCELLED";
|
||||
if (now < startedAt) return "SCHEDULED";
|
||||
if (now <= captureEndsAt) return "RUNNING";
|
||||
if (now <= settleEndsAt) return "DRAINING";
|
||||
return "COMPLETED";
|
||||
}
|
||||
}
|
||||
|
||||
private static final class CapturedLog {
|
||||
private final long sequence;
|
||||
private final String eventId;
|
||||
private final Long deviceId;
|
||||
private final Long deviceCollectId;
|
||||
private final String topic;
|
||||
private final LocalDateTime receivedAt;
|
||||
private final String observedAt;
|
||||
private final String rawMessage;
|
||||
private String processingStatus = "PENDING";
|
||||
private boolean anomaly;
|
||||
private String reason;
|
||||
private String reasonDetail;
|
||||
private String processedAt;
|
||||
|
||||
private CapturedLog(ReceivedLog log) {
|
||||
this.sequence = log.sequence;
|
||||
this.eventId = log.eventId;
|
||||
this.deviceId = log.deviceId;
|
||||
this.deviceCollectId = log.deviceCollectId;
|
||||
this.topic = log.topic;
|
||||
this.receivedAt = log.receivedAt;
|
||||
this.observedAt = instant(log.observedAt);
|
||||
this.rawMessage = log.rawMessage;
|
||||
}
|
||||
|
||||
private CapturedLog copy() {
|
||||
return new CapturedLog(sequence, eventId, deviceId, deviceCollectId, topic,
|
||||
receivedAt, observedAt, rawMessage, processingStatus, anomaly,
|
||||
reason, reasonDetail, processedAt);
|
||||
}
|
||||
|
||||
private CapturedLog(long sequence, String eventId, Long deviceId, Long deviceCollectId,
|
||||
String topic, LocalDateTime receivedAt, String observedAt,
|
||||
String rawMessage, String processingStatus, boolean anomaly,
|
||||
String reason, String reasonDetail, String processedAt) {
|
||||
this.sequence = sequence;
|
||||
this.eventId = eventId;
|
||||
this.deviceId = deviceId;
|
||||
this.deviceCollectId = deviceCollectId;
|
||||
this.topic = topic;
|
||||
this.receivedAt = receivedAt;
|
||||
this.observedAt = observedAt;
|
||||
this.rawMessage = rawMessage;
|
||||
this.processingStatus = processingStatus;
|
||||
this.anomaly = anomaly;
|
||||
this.reason = reason;
|
||||
this.reasonDetail = reasonDetail;
|
||||
this.processedAt = processedAt;
|
||||
}
|
||||
|
||||
private void update(String status, boolean anomaly, String reason, String detail, long now) {
|
||||
if (this.anomaly && !anomaly) return;
|
||||
this.processingStatus = status;
|
||||
this.anomaly = anomaly;
|
||||
this.reason = reason;
|
||||
this.reasonDetail = detail;
|
||||
this.processedAt = instant(now);
|
||||
}
|
||||
|
||||
private CapturedLogSnapshot snapshot() {
|
||||
return new CapturedLogSnapshot(sequence, eventId, deviceId, deviceCollectId, topic,
|
||||
receivedAt, observedAt, processingStatus, anomaly, reason, reasonDetail,
|
||||
processedAt, rawMessage);
|
||||
}
|
||||
}
|
||||
|
||||
static final class CaptureCandidates {
|
||||
private final String sessionId;
|
||||
private final long deviceId;
|
||||
private final long startedAt;
|
||||
private final long captureEndsAt;
|
||||
private final long settleEndsAt;
|
||||
private final int messageCount;
|
||||
private final long receivedCount;
|
||||
private final long processedCount;
|
||||
private final long observedAnomalyCount;
|
||||
private final List<CapturedLogSnapshot> firstMessages;
|
||||
private final List<CapturedLogSnapshot> firstAnomalies;
|
||||
private final long revision;
|
||||
|
||||
CaptureCandidates(String sessionId, long deviceId, long startedAt, long captureEndsAt,
|
||||
long settleEndsAt, int messageCount, long receivedCount,
|
||||
long processedCount, long observedAnomalyCount,
|
||||
List<CapturedLogSnapshot> firstMessages,
|
||||
List<CapturedLogSnapshot> firstAnomalies, long revision) {
|
||||
this.sessionId = sessionId;
|
||||
this.deviceId = deviceId;
|
||||
this.startedAt = startedAt;
|
||||
this.captureEndsAt = captureEndsAt;
|
||||
this.settleEndsAt = settleEndsAt;
|
||||
this.messageCount = messageCount;
|
||||
this.receivedCount = receivedCount;
|
||||
this.processedCount = processedCount;
|
||||
this.observedAnomalyCount = observedAnomalyCount;
|
||||
this.firstMessages = firstMessages;
|
||||
this.firstAnomalies = firstAnomalies;
|
||||
this.revision = revision;
|
||||
}
|
||||
|
||||
String getSessionId() { return sessionId; }
|
||||
long getDeviceId() { return deviceId; }
|
||||
long getStartedAt() { return startedAt; }
|
||||
long getCaptureEndsAt() { return captureEndsAt; }
|
||||
long getSettleEndsAt() { return settleEndsAt; }
|
||||
int getMessageCount() { return messageCount; }
|
||||
long getReceivedCount() { return receivedCount; }
|
||||
long getProcessedCount() { return processedCount; }
|
||||
long getObservedAnomalyCount() { return observedAnomalyCount; }
|
||||
List<CapturedLogSnapshot> getFirstMessages() { return firstMessages; }
|
||||
List<CapturedLogSnapshot> getFirstAnomalies() { return firstAnomalies; }
|
||||
long getRevision() { return revision; }
|
||||
}
|
||||
|
||||
public static final class CaptureSnapshot {
|
||||
private final String sessionId;
|
||||
private final long deviceId;
|
||||
private final String status;
|
||||
private final String startedAt;
|
||||
private final String captureEndsAt;
|
||||
private final String settleEndsAt;
|
||||
private final int messageCount;
|
||||
private final long receivedCount;
|
||||
private final long processedCount;
|
||||
private final long observedAnomalyCount;
|
||||
private final int retainedAnomalyCount;
|
||||
private final long replacementCount;
|
||||
private final List<CapturedLogSnapshot> messages;
|
||||
|
||||
CaptureSnapshot(String sessionId, long deviceId, String status, String startedAt,
|
||||
String captureEndsAt, String settleEndsAt, int messageCount,
|
||||
long receivedCount, long processedCount, long observedAnomalyCount,
|
||||
int retainedAnomalyCount, long replacementCount,
|
||||
List<CapturedLogSnapshot> messages) {
|
||||
this.sessionId = sessionId;
|
||||
this.deviceId = deviceId;
|
||||
this.status = status;
|
||||
this.startedAt = startedAt;
|
||||
this.captureEndsAt = captureEndsAt;
|
||||
this.settleEndsAt = settleEndsAt;
|
||||
this.messageCount = messageCount;
|
||||
this.receivedCount = receivedCount;
|
||||
this.processedCount = processedCount;
|
||||
this.observedAnomalyCount = observedAnomalyCount;
|
||||
this.retainedAnomalyCount = retainedAnomalyCount;
|
||||
this.replacementCount = replacementCount;
|
||||
this.messages = Collections.unmodifiableList(messages);
|
||||
}
|
||||
|
||||
public String getSessionId() { return sessionId; }
|
||||
public long getDeviceId() { return deviceId; }
|
||||
public String getStatus() { return status; }
|
||||
public String getStartedAt() { return startedAt; }
|
||||
public String getCaptureEndsAt() { return captureEndsAt; }
|
||||
public String getSettleEndsAt() { return settleEndsAt; }
|
||||
public int getMessageCount() { return messageCount; }
|
||||
public long getReceivedCount() { return receivedCount; }
|
||||
public long getProcessedCount() { return processedCount; }
|
||||
public long getObservedAnomalyCount() { return observedAnomalyCount; }
|
||||
public int getRetainedAnomalyCount() { return retainedAnomalyCount; }
|
||||
public long getReplacementCount() { return replacementCount; }
|
||||
public List<CapturedLogSnapshot> getMessages() { return messages; }
|
||||
}
|
||||
|
||||
public static final class CapturedLogSnapshot {
|
||||
private final long sequence;
|
||||
private final String eventId;
|
||||
private final Long deviceId;
|
||||
private final Long deviceCollectId;
|
||||
private final String topic;
|
||||
private final LocalDateTime receivedAt;
|
||||
private final String observedAt;
|
||||
private final String processingStatus;
|
||||
private final boolean anomaly;
|
||||
private final String reason;
|
||||
private final String reasonDetail;
|
||||
private final String processedAt;
|
||||
private final String rawMessage;
|
||||
|
||||
CapturedLogSnapshot(long sequence, String eventId, Long deviceId,
|
||||
Long deviceCollectId, String topic, LocalDateTime receivedAt,
|
||||
String observedAt, String processingStatus, boolean anomaly,
|
||||
String reason, String reasonDetail, String processedAt,
|
||||
String rawMessage) {
|
||||
this.sequence = sequence;
|
||||
this.eventId = eventId;
|
||||
this.deviceId = deviceId;
|
||||
this.deviceCollectId = deviceCollectId;
|
||||
this.topic = topic;
|
||||
this.receivedAt = receivedAt;
|
||||
this.observedAt = observedAt;
|
||||
this.processingStatus = processingStatus;
|
||||
this.anomaly = anomaly;
|
||||
this.reason = reason;
|
||||
this.reasonDetail = reasonDetail;
|
||||
this.processedAt = processedAt;
|
||||
this.rawMessage = rawMessage;
|
||||
}
|
||||
|
||||
public long getSequence() { return sequence; }
|
||||
public String getEventId() { return eventId; }
|
||||
public Long getDeviceId() { return deviceId; }
|
||||
public Long getDeviceCollectId() { return deviceCollectId; }
|
||||
public String getTopic() { return topic; }
|
||||
public LocalDateTime getReceivedAt() { return receivedAt; }
|
||||
public String getObservedAt() { return observedAt; }
|
||||
public String getProcessingStatus() { return processingStatus; }
|
||||
public boolean isAnomaly() { return anomaly; }
|
||||
public String getReason() { return reason; }
|
||||
public String getReasonDetail() { return reasonDetail; }
|
||||
public String getProcessedAt() { return processedAt; }
|
||||
public String getRawMessage() { return rawMessage; }
|
||||
}
|
||||
|
||||
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
public static final class CaptureDisabledException extends RuntimeException {
|
||||
public CaptureDisabledException() { super("现场原始日志采样功能未启用"); }
|
||||
}
|
||||
|
||||
@ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
|
||||
public static final class CaptureCapacityException extends RuntimeException {
|
||||
public CaptureCapacityException(int max) { super("采样会话容量已达到上限: " + max); }
|
||||
}
|
||||
|
||||
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
public static final class CaptureCoordinationException extends RuntimeException {
|
||||
public CaptureCoordinationException(Throwable cause) {
|
||||
super("跨实例原始日志采样暂不可用,请检查 Redis 连接", cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.kafka.clients.producer.ProducerConfig;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
|
||||
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
|
||||
import org.springframework.kafka.core.KafkaTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/** 连续消费优先:事实提交后只做有界内存offer,Kafka发送与重试在独立线程执行。 */
|
||||
@Slf4j
|
||||
@Component
|
||||
public class StatsProjectionAsyncPublisher {
|
||||
private final KafkaTemplate<String, String> kafka;
|
||||
private final ObjectMapper mapper;
|
||||
private final ArrayBlockingQueue<Pending> queue;
|
||||
private final long maxPendingGroups;
|
||||
private final AtomicLong pendingGroups = new AtomicLong();
|
||||
private final AtomicLong enqueued = new AtomicLong();
|
||||
private final AtomicLong published = new AtomicLong();
|
||||
private final AtomicLong failures = new AtomicLong();
|
||||
private final AtomicLong droppedEvents = new AtomicLong();
|
||||
private final AtomicLong droppedFactRows = new AtomicLong();
|
||||
private final AtomicLong nextLossLogAt = new AtomicLong();
|
||||
private volatile boolean closed;
|
||||
private volatile Pending inFlight;
|
||||
private ScheduledExecutorService executor;
|
||||
private DefaultKafkaProducerFactory<String, String> ownedProducerFactory;
|
||||
|
||||
// 与旧统计路径使用相同的 mapper;显式区分 WebConfig 的 httpObjectMapper。
|
||||
// 下方构造器复制后关闭类型信息,不修改共享缓存 mapper。
|
||||
@Autowired
|
||||
public StatsProjectionAsyncPublisher(KafkaProperties properties,
|
||||
@Qualifier("objectMapper") ObjectMapper mapper,
|
||||
@Value("${stats.projection-async.memory-queue-capacity:1000}") int capacity,
|
||||
@Value("${stats.projection-async.memory-max-pending-groups:50000}") long maxPendingGroups) {
|
||||
this(dedicatedFactory(properties), mapper, capacity, maxPendingGroups);
|
||||
}
|
||||
|
||||
private StatsProjectionAsyncPublisher(DefaultKafkaProducerFactory<String, String> factory,
|
||||
ObjectMapper mapper, int capacity, long maxPendingGroups) {
|
||||
this(new KafkaTemplate<>(factory), mapper, capacity, maxPendingGroups);
|
||||
this.ownedProducerFactory = factory;
|
||||
}
|
||||
|
||||
private static DefaultKafkaProducerFactory<String, String> dedicatedFactory(KafkaProperties properties) {
|
||||
Map<String, Object> config = new LinkedHashMap<>(properties.buildProducerProperties());
|
||||
config.put(ProducerConfig.CLIENT_ID_CONFIG, "syslog-stats-projection-memory");
|
||||
// 不与主业务Retry/DLT/告警发送共用KafkaProducer缓冲区,统计断链只影响后台发送。
|
||||
return new DefaultKafkaProducerFactory<>(config);
|
||||
}
|
||||
|
||||
@Value("${stats.projection-async.enabled:true}") private boolean enabled;
|
||||
@Value("${stats.projection-async.topic:${spring.kafka.consumer.topic}.STATS.PROJECTION}") private String topic;
|
||||
@Value("${stats.projection-async.publish-timeout-ms:10000}") private long timeoutMs;
|
||||
@Value("${stats.projection-async.retry-backoff-ms:1000}") private long retryBackoffMs;
|
||||
|
||||
StatsProjectionAsyncPublisher(KafkaTemplate<String, String> kafka, ObjectMapper mapper,
|
||||
int capacity, long maxPendingGroups) {
|
||||
if (capacity < 1 || maxPendingGroups < 1) throw new IllegalArgumentException("统计内存队列容量必须大于0");
|
||||
this.kafka = kafka;
|
||||
this.mapper = mapper.copy();
|
||||
this.mapper.deactivateDefaultTyping();
|
||||
this.queue = new ArrayBlockingQueue<>(capacity);
|
||||
this.maxPendingGroups = maxPendingGroups;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void start() {
|
||||
executor = Executors.newSingleThreadScheduledExecutor(task -> {
|
||||
Thread thread = new Thread(task, "stats-projection-publisher");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
executor.scheduleWithFixedDelay(this::flush, 0, 200, TimeUnit.MILLISECONDS);
|
||||
log.info("Stats projection publisher ready: mode=BEST_EFFORT_AFTER_COMMIT_KAFKA, enabled={}, "
|
||||
+ "queueCapacity={}, maxPendingGroups={}, topic={}",
|
||||
enabled, queue.remainingCapacity(), maxPendingGroups, topic);
|
||||
}
|
||||
|
||||
public void enqueueAfterCommit(StatsProjectionOutboxEvent event, int factRows) {
|
||||
try {
|
||||
event.validate();
|
||||
event.setOutboxBacked(false);
|
||||
if (!TransactionSynchronizationManager.isActualTransactionActive()
|
||||
|| !TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
throw new IllegalStateException("统计事件必须在事实事务提交后入队");
|
||||
}
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override public void afterCommit() {
|
||||
// 不做序列化、网络发送或数据库写入,任何运行时失败均不得影响已提交事实。
|
||||
offer(event, factRows);
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException failure) {
|
||||
recordLoss(factRows, "PREPARE_OR_REGISTER_FAILED", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private void offer(StatsProjectionOutboxEvent event, int factRows) {
|
||||
long groups = (long) event.getDevices().size() + event.getRules().size() + event.getCollects().size();
|
||||
boolean reserved = false;
|
||||
try {
|
||||
if (!enabled || closed) {
|
||||
recordLoss(factRows, closed ? "SHUTTING_DOWN" : "PROJECTION_DISABLED", null);
|
||||
return;
|
||||
}
|
||||
long current;
|
||||
do {
|
||||
current = pendingGroups.get();
|
||||
if (groups > maxPendingGroups - current) {
|
||||
recordLoss(factRows, "GROUP_CAPACITY", null);
|
||||
return;
|
||||
}
|
||||
} while (!pendingGroups.compareAndSet(current, current + groups));
|
||||
reserved = true;
|
||||
if (queue.offer(new Pending(event, groups))) {
|
||||
reserved = false; // 预算归队列/发送线程所有,发送成功后释放。
|
||||
enqueued.incrementAndGet();
|
||||
} else {
|
||||
recordLoss(factRows, "QUEUE_FULL", null);
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
recordLoss(factRows, "ENQUEUE_FAILED", failure);
|
||||
} finally {
|
||||
if (reserved) pendingGroups.addAndGet(-groups);
|
||||
}
|
||||
}
|
||||
|
||||
/** 独立线程每轮最多发送100个聚合事件;失败保留原eventId,下游可去重。 */
|
||||
synchronized void flush() {
|
||||
if (!enabled || closed) return;
|
||||
for (int i = 0; i < 100 && !closed; i++) {
|
||||
if (inFlight == null) inFlight = queue.poll();
|
||||
Pending pending = inFlight;
|
||||
if (pending == null || pending.retryAt > System.currentTimeMillis()) return;
|
||||
try {
|
||||
if (pending.payload == null) pending.payload = mapper.writeValueAsString(pending.event);
|
||||
kafka.send(topic, StatsProjectionOutboxEvent.KAFKA_KEY, pending.payload)
|
||||
.get(Math.max(1L, timeoutMs), TimeUnit.MILLISECONDS);
|
||||
published.incrementAndGet();
|
||||
pendingGroups.addAndGet(-pending.groups);
|
||||
inFlight = null;
|
||||
} catch (Exception failure) {
|
||||
failures.incrementAndGet();
|
||||
pending.retryAt = System.currentTimeMillis() + Math.max(1000L, retryBackoffMs);
|
||||
log.warn("[STATS_ASYNC_PUBLISH_FAILED] eventId={}, pendingEvents={}, action=BACKGROUND_RETRY, errorType={}",
|
||||
pending.event.getEventId(), queue.size() + 1, failure.getClass().getName());
|
||||
if (failure instanceof InterruptedException) Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void recordLoss(int factRows, String reason, RuntimeException failure) {
|
||||
droppedEvents.incrementAndGet();
|
||||
droppedFactRows.addAndGet(Math.max(0, factRows));
|
||||
long now = System.currentTimeMillis();
|
||||
long next = nextLossLogAt.get();
|
||||
if (now >= next && nextLossLogAt.compareAndSet(next, now + 10000L)) {
|
||||
log.error("[STATS_ASYNC_LOSS] reason={}, droppedEventsTotal={}, droppedFactRowsTotal={}, "
|
||||
+ "action=CONTINUE_FACT_CONSUMPTION, errorType={}", reason, droppedEvents.get(),
|
||||
droppedFactRows.get(), failure == null ? "none" : failure.getClass().getName());
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("mode", "BEST_EFFORT_AFTER_COMMIT_KAFKA");
|
||||
result.put("enabled", enabled);
|
||||
result.put("topic", topic);
|
||||
result.put("pending_events", queue.size() + (inFlight == null ? 0 : 1));
|
||||
result.put("queue_capacity", queue.size() + queue.remainingCapacity());
|
||||
result.put("pending_groups", pendingGroups.get());
|
||||
result.put("max_pending_groups", maxPendingGroups);
|
||||
result.put("enqueued_total", enqueued.get());
|
||||
result.put("published_total", published.get());
|
||||
result.put("publish_failures_total", failures.get());
|
||||
result.put("dropped_events_total", droppedEvents.get());
|
||||
result.put("dropped_fact_rows_total", droppedFactRows.get());
|
||||
return result;
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void stop() {
|
||||
closed = true;
|
||||
if (executor != null) executor.shutdownNow();
|
||||
int pending = queue.size() + (inFlight == null ? 0 : 1);
|
||||
if (pending > 0) log.warn("[STATS_ASYNC_SHUTDOWN_PENDING] pendingEvents={}, "
|
||||
+ "pendingGroups={}, action=STATISTICS_MAY_BE_LOST", pending, pendingGroups.get());
|
||||
if (ownedProducerFactory != null) ownedProducerFactory.destroy();
|
||||
}
|
||||
|
||||
private static final class Pending {
|
||||
final StatsProjectionOutboxEvent event;
|
||||
final long groups;
|
||||
String payload;
|
||||
long retryAt;
|
||||
Pending(StatsProjectionOutboxEvent event, long groups) { this.event = event; this.groups = groups; }
|
||||
}
|
||||
}
|
||||
+386
@@ -0,0 +1,386 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.kafka.annotation.KafkaListener;
|
||||
import org.springframework.kafka.support.Acknowledgment;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.sql.Date;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/** Applies durable projection deltas outside the fact transaction. */
|
||||
@Slf4j
|
||||
@Component
|
||||
public class StatsProjectionDeltaConsumer {
|
||||
private static final String DEVICE_MERGE =
|
||||
"MERGE INTO %s t USING (SELECT ? stat_date,? device_id,? parse_delta," +
|
||||
"? non_log_delta,? receive_time FROM DUAL) s " +
|
||||
"ON (t.stat_date=s.stat_date AND t.device_id=s.device_id) " +
|
||||
"WHEN MATCHED THEN UPDATE SET t.parse_count=t.parse_count+s.parse_delta," +
|
||||
"t.non_log_count=t.non_log_count+s.non_log_delta," +
|
||||
"t.last_receive_time=CASE WHEN s.receive_time IS NULL THEN t.last_receive_time " +
|
||||
"WHEN t.last_receive_time IS NULL OR t.last_receive_time<s.receive_time " +
|
||||
"THEN s.receive_time ELSE t.last_receive_time END," +
|
||||
"t.projection_seq=t.projection_seq+1,t.updated_at=SYSDATE " +
|
||||
"WHEN NOT MATCHED THEN INSERT (stat_date,device_id,parse_count,non_log_count," +
|
||||
"last_receive_time,projection_seq,updated_at) VALUES " +
|
||||
"(s.stat_date,s.device_id,s.parse_delta,s.non_log_delta,s.receive_time,1,SYSDATE)";
|
||||
|
||||
private static final String RULE_MERGE =
|
||||
"MERGE INTO %s t USING (SELECT ? stat_date,? normalize_rule_id,? max_log_time FROM DUAL) s " +
|
||||
"ON (t.stat_date=s.stat_date AND t.normalize_rule_id=s.normalize_rule_id) " +
|
||||
"WHEN MATCHED THEN UPDATE SET t.max_log_time=CASE " +
|
||||
"WHEN t.max_log_time IS NULL OR t.max_log_time<s.max_log_time THEN s.max_log_time " +
|
||||
"ELSE t.max_log_time END,t.projection_seq=t.projection_seq+1,t.updated_at=SYSDATE " +
|
||||
"WHEN NOT MATCHED THEN INSERT (stat_date,normalize_rule_id,max_log_time,projection_seq,updated_at) " +
|
||||
"VALUES (s.stat_date,s.normalize_rule_id,s.max_log_time,1,SYSDATE)";
|
||||
|
||||
private static final String COLLECT_MERGE =
|
||||
"MERGE INTO device_collect_stats t USING (SELECT ? device_collect_id," +
|
||||
"? first_success_time,? last_success_time FROM DUAL) s " +
|
||||
"ON (t.device_collect_id=s.device_collect_id) " +
|
||||
"WHEN MATCHED THEN UPDATE SET t.first_success_time=CASE " +
|
||||
"WHEN s.first_success_time IS NULL THEN t.first_success_time " +
|
||||
"WHEN t.first_success_time IS NULL OR t.first_success_time>s.first_success_time " +
|
||||
"THEN s.first_success_time ELSE t.first_success_time END," +
|
||||
"t.last_success_time=CASE WHEN s.last_success_time IS NULL THEN t.last_success_time " +
|
||||
"WHEN t.last_success_time IS NULL OR t.last_success_time<s.last_success_time " +
|
||||
"THEN s.last_success_time ELSE t.last_success_time END," +
|
||||
"t.projection_seq=t.projection_seq+1,t.updated_at=SYSDATE " +
|
||||
"WHEN NOT MATCHED THEN INSERT (device_collect_id,first_success_time,last_success_time," +
|
||||
"last_fail_time,projection_seq,updated_at) VALUES " +
|
||||
"(s.device_collect_id,s.first_success_time,s.last_success_time,NULL,1,SYSDATE)";
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final StatsMaterializationPublisher materializationPublisher;
|
||||
|
||||
@Value("${stats.projection-async.enabled:true}") private boolean enabled;
|
||||
@Value("${stats.projection-async.applied-table:stats_projection_applied_event}") private String appliedTable;
|
||||
@Value("${stats.projection-async.outbox-table:stats_projection_outbox}") private String outboxTable;
|
||||
@Value("${stats.direct.device-table:device_daily_stats}") private String deviceTable;
|
||||
@Value("${stats.direct.rule-table:normalize_rule_daily_stats}") private String ruleTable;
|
||||
@Value("${stats.incremental.transaction-timeout-seconds:45}") private int transactionTimeoutSeconds;
|
||||
@Value("${stats.projection-async.max-concurrency-retries:3}") private int maxConcurrencyRetries;
|
||||
@Value("${stats.projection-async.concurrency-retry-backoff-ms:50}") private long retryBackoffMs;
|
||||
|
||||
private final AtomicLong consumed = new AtomicLong();
|
||||
private final AtomicLong appliedEvents = new AtomicLong();
|
||||
private final AtomicLong duplicates = new AtomicLong();
|
||||
private final AtomicLong deviceGroups = new AtomicLong();
|
||||
private final AtomicLong ruleGroups = new AtomicLong();
|
||||
private final AtomicLong collectGroups = new AtomicLong();
|
||||
private final AtomicLong successfulBatches = new AtomicLong();
|
||||
private final AtomicLong failures = new AtomicLong();
|
||||
private final AtomicLong retries = new AtomicLong();
|
||||
private volatile LocalDateTime lastSuccessTime;
|
||||
private volatile LocalDateTime lastFailureTime;
|
||||
|
||||
public StatsProjectionDeltaConsumer(JdbcTemplate jdbc,
|
||||
PlatformTransactionManager transactionManager,
|
||||
ObjectMapper objectMapper,
|
||||
StatsMaterializationPublisher materializationPublisher) {
|
||||
this.jdbc = jdbc;
|
||||
this.transactionManager = transactionManager;
|
||||
this.objectMapper = objectMapper.copy();
|
||||
this.objectMapper.deactivateDefaultTyping();
|
||||
this.materializationPublisher = materializationPublisher;
|
||||
}
|
||||
|
||||
@KafkaListener(
|
||||
id = "syslog-stats-projection",
|
||||
groupId = "${stats.projection-async.group-id:${spring.kafka.consumer.group-id}-stats-projection}",
|
||||
topics = "${stats.projection-async.topic:${spring.kafka.consumer.topic}.STATS.PROJECTION}",
|
||||
autoStartup = "${stats.projection-async.enabled:true}",
|
||||
containerFactory = "statsProjectionKafkaListenerContainerFactory"
|
||||
)
|
||||
public void consume(List<ConsumerRecord<String, String>> records, Acknowledgment acknowledgment) {
|
||||
if (records == null || records.isEmpty()) {
|
||||
acknowledgment.acknowledge();
|
||||
return;
|
||||
}
|
||||
consumed.addAndGet(records.size());
|
||||
List<StatsProjectionOutboxEvent> events = parse(records);
|
||||
long started = System.nanoTime();
|
||||
try {
|
||||
ApplyResult result = applyWithRetry(events);
|
||||
acknowledgment.acknowledge();
|
||||
appliedEvents.addAndGet(result.appliedEvents);
|
||||
duplicates.addAndGet(result.duplicates);
|
||||
deviceGroups.addAndGet(result.deviceGroups);
|
||||
ruleGroups.addAndGet(result.ruleGroups);
|
||||
collectGroups.addAndGet(result.collectGroups);
|
||||
successfulBatches.incrementAndGet();
|
||||
lastSuccessTime = LocalDateTime.now();
|
||||
log.info("统计投影批次完成: received={}, appliedEvents={}, duplicates={}, " +
|
||||
"deviceGroups={}, ruleGroups={}, collectGroups={}, durationMs={}",
|
||||
records.size(), result.appliedEvents, result.duplicates,
|
||||
result.deviceGroups, result.ruleGroups, result.collectGroups,
|
||||
(System.nanoTime() - started) / 1_000_000L);
|
||||
} catch (RuntimeException failure) {
|
||||
failures.incrementAndGet();
|
||||
lastFailureTime = LocalDateTime.now();
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private List<StatsProjectionOutboxEvent> parse(List<ConsumerRecord<String, String>> records) {
|
||||
Map<String, StatsProjectionOutboxEvent> unique = new LinkedHashMap<>();
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
try {
|
||||
if (!StatsProjectionOutboxEvent.KAFKA_KEY.equals(record.key())) {
|
||||
throw new IllegalArgumentException("Unexpected stats projection Kafka key: " + record.key());
|
||||
}
|
||||
StatsProjectionOutboxEvent event = objectMapper.readValue(
|
||||
record.value(), StatsProjectionOutboxEvent.class);
|
||||
event.validate();
|
||||
unique.put(event.getEventId(), event);
|
||||
} catch (Exception invalid) {
|
||||
throw new IllegalStateException("Invalid internal stats projection event at " +
|
||||
record.topic() + "-" + record.partition() + "@" + record.offset(), invalid);
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(unique.values());
|
||||
}
|
||||
|
||||
ApplyResult applyWithRetry(List<StatsProjectionOutboxEvent> events) {
|
||||
int attempt = 0;
|
||||
while (true) {
|
||||
try {
|
||||
return applyOnce(events);
|
||||
} catch (RuntimeException failure) {
|
||||
if (!DirectStatsProjectionWriter.isConcurrentFailure(failure)
|
||||
|| attempt >= Math.max(0, maxConcurrencyRetries)) {
|
||||
throw failure;
|
||||
}
|
||||
attempt++;
|
||||
retries.incrementAndGet();
|
||||
sleepBeforeRetry(attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ApplyResult applyOnce(List<StatsProjectionOutboxEvent> events) {
|
||||
if (!enabled) throw new IllegalStateException("Stats projection consumer is disabled");
|
||||
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
|
||||
transaction.setTimeout(Math.max(1, transactionTimeoutSeconds));
|
||||
ApplyResult result = transaction.execute(status -> {
|
||||
Set<String> existing = existingEventIds(events);
|
||||
List<StatsProjectionOutboxEvent> fresh = new ArrayList<>();
|
||||
for (StatsProjectionOutboxEvent event : events) {
|
||||
if (!existing.contains(event.getEventId())) fresh.add(event);
|
||||
}
|
||||
ProjectionAggregation aggregation = aggregate(fresh);
|
||||
if (!aggregation.devices.isEmpty()) {
|
||||
jdbc.batchUpdate(String.format(DEVICE_MERGE,
|
||||
StatsProjectionOutboxWriter.safeTable(deviceTable)), aggregation.deviceParams());
|
||||
}
|
||||
if (!aggregation.rules.isEmpty()) {
|
||||
jdbc.batchUpdate(String.format(RULE_MERGE,
|
||||
StatsProjectionOutboxWriter.safeTable(ruleTable)), aggregation.ruleParams());
|
||||
}
|
||||
if (!aggregation.collects.isEmpty()) {
|
||||
jdbc.batchUpdate(COLLECT_MERGE, aggregation.collectParams());
|
||||
}
|
||||
if (!fresh.isEmpty()) {
|
||||
List<Object[]> markers = new ArrayList<>(fresh.size());
|
||||
for (StatsProjectionOutboxEvent event : fresh) {
|
||||
markers.add(new Object[]{event.getEventId(), event.getSchema()});
|
||||
}
|
||||
jdbc.batchUpdate("INSERT INTO " + StatsProjectionOutboxWriter.safeTable(appliedTable) +
|
||||
" (event_id,event_schema,applied_at) VALUES (?,?,SYSDATE)", markers);
|
||||
}
|
||||
List<Object[]> acknowledged = new ArrayList<>();
|
||||
for (StatsProjectionOutboxEvent event : events) {
|
||||
if (event.isOutboxBacked()) acknowledged.add(new Object[]{event.getEventId()});
|
||||
}
|
||||
if (!acknowledged.isEmpty()) {
|
||||
jdbc.batchUpdate("UPDATE " + StatsProjectionOutboxWriter.safeTable(outboxTable) +
|
||||
" SET status='APPLIED',applied_at=SYSDATE,next_attempt_at=NULL," +
|
||||
"updated_at=SYSDATE WHERE event_id=?", acknowledged);
|
||||
}
|
||||
Collection<StatsMaterializationCommand> dirty = aggregation.materializationCommands();
|
||||
if (!dirty.isEmpty()) materializationPublisher.enqueueAfterCommit(dirty);
|
||||
return new ApplyResult(fresh.size(), events.size() - fresh.size(),
|
||||
aggregation.devices.size(), aggregation.rules.size(), aggregation.collects.size());
|
||||
});
|
||||
return result == null ? new ApplyResult(0, events.size(), 0, 0, 0) : result;
|
||||
}
|
||||
|
||||
private Set<String> existingEventIds(List<StatsProjectionOutboxEvent> events) {
|
||||
if (events.isEmpty()) return Collections.emptySet();
|
||||
Set<String> result = new HashSet<>();
|
||||
int chunkSize = 900;
|
||||
for (int start = 0; start < events.size(); start += chunkSize) {
|
||||
int end = Math.min(events.size(), start + chunkSize);
|
||||
StringBuilder placeholders = new StringBuilder();
|
||||
Object[] ids = new Object[end - start];
|
||||
for (int i = start; i < end; i++) {
|
||||
if (placeholders.length() > 0) placeholders.append(',');
|
||||
placeholders.append('?');
|
||||
ids[i - start] = events.get(i).getEventId();
|
||||
}
|
||||
result.addAll(jdbc.queryForList("SELECT event_id FROM " +
|
||||
StatsProjectionOutboxWriter.safeTable(appliedTable) + " WHERE event_id IN (" +
|
||||
placeholders + ")", String.class, ids));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static ProjectionAggregation aggregate(List<StatsProjectionOutboxEvent> events) {
|
||||
ProjectionAggregation result = new ProjectionAggregation();
|
||||
for (StatsProjectionOutboxEvent event : events) {
|
||||
event.validate();
|
||||
for (StatsProjectionOutboxEvent.DeviceDelta delta : event.getDevices()) {
|
||||
DeviceKey key = new DeviceKey(delta.date(), delta.getDeviceId());
|
||||
DeviceAggregate value = result.devices.computeIfAbsent(key,
|
||||
ignored -> new DeviceAggregate());
|
||||
value.parseDelta += delta.getParseDelta();
|
||||
value.nonLogDelta += delta.getNonLogDelta();
|
||||
LocalDateTime receiveTime = delta.receiveTime();
|
||||
if (receiveTime != null && (value.lastReceiveTime == null
|
||||
|| receiveTime.isAfter(value.lastReceiveTime))) {
|
||||
value.lastReceiveTime = receiveTime;
|
||||
}
|
||||
}
|
||||
for (StatsProjectionOutboxEvent.RuleDelta delta : event.getRules()) {
|
||||
RuleKey key = new RuleKey(delta.date(), delta.getNormalizeRuleId());
|
||||
LocalDateTime value = delta.time();
|
||||
LocalDateTime current = result.rules.get(key);
|
||||
if (current == null || value.isAfter(current)) result.rules.put(key, value);
|
||||
}
|
||||
for (StatsProjectionOutboxEvent.CollectDelta delta : event.getCollects()) {
|
||||
CollectAggregate value = result.collects.computeIfAbsent(delta.getDeviceCollectId(),
|
||||
ignored -> new CollectAggregate());
|
||||
value.include(delta.firstTime());
|
||||
value.include(delta.lastTime());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void sleepBeforeRetry(int attempt) {
|
||||
try {
|
||||
Thread.sleep(Math.max(0L, retryBackoffMs) * attempt);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("Stats projection retry interrupted", interrupted);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("enabled", enabled);
|
||||
result.put("consumed_total", consumed.get());
|
||||
result.put("applied_events_total", appliedEvents.get());
|
||||
result.put("duplicate_events_total", duplicates.get());
|
||||
result.put("device_groups_total", deviceGroups.get());
|
||||
result.put("rule_groups_total", ruleGroups.get());
|
||||
result.put("collect_groups_total", collectGroups.get());
|
||||
result.put("successful_batches", successfulBatches.get());
|
||||
result.put("failures_total", failures.get());
|
||||
result.put("concurrency_retries_total", retries.get());
|
||||
result.put("last_success_time", lastSuccessTime);
|
||||
result.put("last_failure_time", lastFailureTime);
|
||||
return result;
|
||||
}
|
||||
|
||||
static final class ProjectionAggregation {
|
||||
final Map<DeviceKey, DeviceAggregate> devices = new TreeMap<>();
|
||||
final Map<RuleKey, LocalDateTime> rules = new TreeMap<>();
|
||||
final Map<Long, CollectAggregate> collects = new TreeMap<>();
|
||||
|
||||
List<Object[]> deviceParams() {
|
||||
List<Object[]> result = new ArrayList<>(devices.size());
|
||||
for (Map.Entry<DeviceKey, DeviceAggregate> entry : devices.entrySet()) {
|
||||
DeviceAggregate value = entry.getValue();
|
||||
result.add(new Object[]{Date.valueOf(entry.getKey().date), entry.getKey().id,
|
||||
value.parseDelta, value.nonLogDelta, value.lastReceiveTime});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
List<Object[]> ruleParams() {
|
||||
List<Object[]> result = new ArrayList<>(rules.size());
|
||||
for (Map.Entry<RuleKey, LocalDateTime> entry : rules.entrySet()) {
|
||||
result.add(new Object[]{Date.valueOf(entry.getKey().date), entry.getKey().id,
|
||||
entry.getValue()});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
List<Object[]> collectParams() {
|
||||
List<Object[]> result = new ArrayList<>(collects.size());
|
||||
for (Map.Entry<Long, CollectAggregate> entry : collects.entrySet()) {
|
||||
result.add(new Object[]{entry.getKey(), entry.getValue().min, entry.getValue().max});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Collection<StatsMaterializationCommand> materializationCommands() {
|
||||
Set<StatsMaterializationCommand> result = new LinkedHashSet<>();
|
||||
for (DeviceKey key : devices.keySet()) result.add(StatsMaterializationCommand.device(key.date, key.id));
|
||||
for (RuleKey key : rules.keySet()) result.add(StatsMaterializationCommand.rule(key.date, key.id));
|
||||
for (Long id : collects.keySet()) result.add(StatsMaterializationCommand.collect(id));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
static class DimensionKey implements Comparable<DimensionKey> {
|
||||
final LocalDate date;
|
||||
final long id;
|
||||
DimensionKey(LocalDate date, long id) { this.date = date; this.id = id; }
|
||||
@Override public int compareTo(DimensionKey other) {
|
||||
int dateOrder = date.compareTo(other.date);
|
||||
return dateOrder != 0 ? dateOrder : Long.compare(id, other.id);
|
||||
}
|
||||
@Override public boolean equals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof DimensionKey)) return false;
|
||||
DimensionKey key = (DimensionKey) other;
|
||||
return id == key.id && date.equals(key.date);
|
||||
}
|
||||
@Override public int hashCode() { return 31 * date.hashCode() + Long.hashCode(id); }
|
||||
}
|
||||
static final class DeviceKey extends DimensionKey { DeviceKey(LocalDate date, long id) { super(date, id); } }
|
||||
static final class RuleKey extends DimensionKey { RuleKey(LocalDate date, long id) { super(date, id); } }
|
||||
static final class DeviceAggregate { long parseDelta; long nonLogDelta; LocalDateTime lastReceiveTime; }
|
||||
static final class CollectAggregate {
|
||||
LocalDateTime min; LocalDateTime max;
|
||||
void include(LocalDateTime time) {
|
||||
if (time == null) return;
|
||||
if (min == null || time.isBefore(min)) min = time;
|
||||
if (max == null || time.isAfter(max)) max = time;
|
||||
}
|
||||
}
|
||||
|
||||
static final class ApplyResult {
|
||||
final int appliedEvents; final int duplicates;
|
||||
final int deviceGroups; final int ruleGroups; final int collectGroups;
|
||||
ApplyResult(int appliedEvents, int duplicates, int deviceGroups, int ruleGroups, int collectGroups) {
|
||||
this.appliedEvents = appliedEvents; this.duplicates = duplicates;
|
||||
this.deviceGroups = deviceGroups; this.ruleGroups = ruleGroups; this.collectGroups = collectGroups;
|
||||
}
|
||||
}
|
||||
}
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Batch-aggregated delta shared by the after-commit memory publisher and legacy durable Outbox.
|
||||
*
|
||||
* <p>The event is additive/max-min only, so events from different application nodes may be
|
||||
* published in a different order without changing the final projection. Kafka duplicates are
|
||||
* eliminated by {@code eventId} in the projection consumer transaction.</p>
|
||||
*/
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class StatsProjectionOutboxEvent {
|
||||
public static final String SCHEMA = "SYSLOG_STATS_PROJECTION_V1";
|
||||
public static final String KAFKA_KEY = "SYSLOG_STATS_PROJECTION";
|
||||
|
||||
private String schema = SCHEMA;
|
||||
private String eventId = UUID.randomUUID().toString();
|
||||
// 老版消息没有此字段,默认true,兼容清理升级前的Outbox。
|
||||
private boolean outboxBacked = true;
|
||||
|
||||
public boolean isOutboxBacked() { return outboxBacked; }
|
||||
public void setOutboxBacked(boolean outboxBacked) { this.outboxBacked = outboxBacked; }
|
||||
private List<DeviceDelta> devices = new ArrayList<>();
|
||||
private List<RuleDelta> rules = new ArrayList<>();
|
||||
private List<CollectDelta> collects = new ArrayList<>();
|
||||
|
||||
public static StatsProjectionOutboxEvent fromAccumulator(DirectStatsAccumulator accumulator) {
|
||||
StatsProjectionOutboxEvent event = new StatsProjectionOutboxEvent();
|
||||
for (Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta> entry
|
||||
: accumulator.getDevices().entrySet()) {
|
||||
DirectStatsAccumulator.DeviceDelta value = entry.getValue();
|
||||
if (value.getParseDelta() != 0L || value.getNonLogDelta() != 0L) {
|
||||
event.devices.add(DeviceDelta.counts(entry.getKey().getDate(),
|
||||
entry.getKey().getDimensionId(), value.getParseDelta(), value.getNonLogDelta()));
|
||||
}
|
||||
}
|
||||
for (Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta> entry
|
||||
: accumulator.getRules().entrySet()) {
|
||||
if (entry.getValue().getMaxLogTime() != null) {
|
||||
event.rules.add(RuleDelta.max(entry.getKey().getDate(),
|
||||
entry.getKey().getDimensionId(), entry.getValue().getMaxLogTime()));
|
||||
}
|
||||
}
|
||||
return event;
|
||||
}
|
||||
|
||||
static StatsProjectionOutboxEvent fromIngress(IngressStatsProjectionWriter.Aggregation aggregation) {
|
||||
StatsProjectionOutboxEvent event = new StatsProjectionOutboxEvent();
|
||||
for (Map.Entry<IngressStatsProjectionWriter.DeviceKey, LocalDateTime> entry
|
||||
: aggregation.devices.entrySet()) {
|
||||
event.devices.add(DeviceDelta.received(entry.getKey().date,
|
||||
entry.getKey().deviceId, entry.getValue()));
|
||||
}
|
||||
for (Map.Entry<Long, IngressStatsProjectionWriter.CollectTimes> entry
|
||||
: aggregation.collects.entrySet()) {
|
||||
event.collects.add(CollectDelta.range(entry.getKey(),
|
||||
entry.getValue().min, entry.getValue().max));
|
||||
}
|
||||
return event;
|
||||
}
|
||||
|
||||
public void validate() {
|
||||
if (!SCHEMA.equals(schema)) {
|
||||
throw new IllegalArgumentException("Unsupported stats projection schema: " + schema);
|
||||
}
|
||||
if (eventId == null || eventId.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("Stats projection event is missing eventId");
|
||||
}
|
||||
if (devices == null || rules == null || collects == null) {
|
||||
throw new IllegalArgumentException("Stats projection event contains null collections");
|
||||
}
|
||||
if (devices.isEmpty() && rules.isEmpty() && collects.isEmpty()) {
|
||||
throw new IllegalArgumentException("Stats projection event has no changes");
|
||||
}
|
||||
for (DeviceDelta delta : devices) delta.validate();
|
||||
for (RuleDelta delta : rules) delta.validate();
|
||||
for (CollectDelta delta : collects) delta.validate();
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return devices.isEmpty() && rules.isEmpty() && collects.isEmpty();
|
||||
}
|
||||
|
||||
public String getSchema() { return schema; }
|
||||
public void setSchema(String schema) { this.schema = schema; }
|
||||
public String getEventId() { return eventId; }
|
||||
public void setEventId(String eventId) { this.eventId = eventId; }
|
||||
public List<DeviceDelta> getDevices() { return devices; }
|
||||
public void setDevices(List<DeviceDelta> devices) { this.devices = devices; }
|
||||
public List<RuleDelta> getRules() { return rules; }
|
||||
public void setRules(List<RuleDelta> rules) { this.rules = rules; }
|
||||
public List<CollectDelta> getCollects() { return collects; }
|
||||
public void setCollects(List<CollectDelta> collects) { this.collects = collects; }
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class DeviceDelta {
|
||||
private String statDate;
|
||||
private long deviceId;
|
||||
private long parseDelta;
|
||||
private long nonLogDelta;
|
||||
private String lastReceiveTime;
|
||||
|
||||
public DeviceDelta() {}
|
||||
|
||||
static DeviceDelta counts(LocalDate date, long deviceId, long parseDelta, long nonLogDelta) {
|
||||
DeviceDelta result = new DeviceDelta();
|
||||
result.statDate = date.toString();
|
||||
result.deviceId = deviceId;
|
||||
result.parseDelta = parseDelta;
|
||||
result.nonLogDelta = nonLogDelta;
|
||||
return result;
|
||||
}
|
||||
|
||||
static DeviceDelta received(LocalDate date, long deviceId, LocalDateTime receiveTime) {
|
||||
DeviceDelta result = counts(date, deviceId, 0L, 0L);
|
||||
result.lastReceiveTime = receiveTime.toString();
|
||||
return result;
|
||||
}
|
||||
|
||||
void validate() {
|
||||
date();
|
||||
if (deviceId <= 0L) throw new IllegalArgumentException("Invalid device projection id");
|
||||
if (parseDelta == 0L && nonLogDelta == 0L && receiveTime() == null) {
|
||||
throw new IllegalArgumentException("Device projection delta is empty");
|
||||
}
|
||||
}
|
||||
|
||||
public LocalDate date() { return LocalDate.parse(statDate); }
|
||||
public LocalDateTime receiveTime() {
|
||||
return lastReceiveTime == null || lastReceiveTime.trim().isEmpty()
|
||||
? null : LocalDateTime.parse(lastReceiveTime);
|
||||
}
|
||||
public String getStatDate() { return statDate; }
|
||||
public void setStatDate(String statDate) { this.statDate = statDate; }
|
||||
public long getDeviceId() { return deviceId; }
|
||||
public void setDeviceId(long deviceId) { this.deviceId = deviceId; }
|
||||
public long getParseDelta() { return parseDelta; }
|
||||
public void setParseDelta(long parseDelta) { this.parseDelta = parseDelta; }
|
||||
public long getNonLogDelta() { return nonLogDelta; }
|
||||
public void setNonLogDelta(long nonLogDelta) { this.nonLogDelta = nonLogDelta; }
|
||||
public String getLastReceiveTime() { return lastReceiveTime; }
|
||||
public void setLastReceiveTime(String lastReceiveTime) { this.lastReceiveTime = lastReceiveTime; }
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class RuleDelta {
|
||||
private String statDate;
|
||||
private long normalizeRuleId;
|
||||
private String maxLogTime;
|
||||
|
||||
public RuleDelta() {}
|
||||
|
||||
static RuleDelta max(LocalDate date, long ruleId, LocalDateTime maxLogTime) {
|
||||
RuleDelta result = new RuleDelta();
|
||||
result.statDate = date.toString();
|
||||
result.normalizeRuleId = ruleId;
|
||||
result.maxLogTime = maxLogTime.toString();
|
||||
return result;
|
||||
}
|
||||
|
||||
void validate() {
|
||||
date();
|
||||
if (normalizeRuleId <= 0L || time() == null) {
|
||||
throw new IllegalArgumentException("Invalid rule projection delta");
|
||||
}
|
||||
}
|
||||
|
||||
public LocalDate date() { return LocalDate.parse(statDate); }
|
||||
public LocalDateTime time() {
|
||||
return maxLogTime == null || maxLogTime.trim().isEmpty()
|
||||
? null : LocalDateTime.parse(maxLogTime);
|
||||
}
|
||||
public String getStatDate() { return statDate; }
|
||||
public void setStatDate(String statDate) { this.statDate = statDate; }
|
||||
public long getNormalizeRuleId() { return normalizeRuleId; }
|
||||
public void setNormalizeRuleId(long normalizeRuleId) { this.normalizeRuleId = normalizeRuleId; }
|
||||
public String getMaxLogTime() { return maxLogTime; }
|
||||
public void setMaxLogTime(String maxLogTime) { this.maxLogTime = maxLogTime; }
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CollectDelta {
|
||||
private long deviceCollectId;
|
||||
private String firstSuccessTime;
|
||||
private String lastSuccessTime;
|
||||
|
||||
public CollectDelta() {}
|
||||
|
||||
static CollectDelta range(long collectId, LocalDateTime first, LocalDateTime last) {
|
||||
CollectDelta result = new CollectDelta();
|
||||
result.deviceCollectId = collectId;
|
||||
result.firstSuccessTime = first == null ? null : first.toString();
|
||||
result.lastSuccessTime = last == null ? null : last.toString();
|
||||
return result;
|
||||
}
|
||||
|
||||
void validate() {
|
||||
if (deviceCollectId <= 0L || (firstTime() == null && lastTime() == null)) {
|
||||
throw new IllegalArgumentException("Invalid collector projection delta");
|
||||
}
|
||||
}
|
||||
|
||||
public LocalDateTime firstTime() {
|
||||
return firstSuccessTime == null || firstSuccessTime.trim().isEmpty()
|
||||
? null : LocalDateTime.parse(firstSuccessTime);
|
||||
}
|
||||
public LocalDateTime lastTime() {
|
||||
return lastSuccessTime == null || lastSuccessTime.trim().isEmpty()
|
||||
? null : LocalDateTime.parse(lastSuccessTime);
|
||||
}
|
||||
public long getDeviceCollectId() { return deviceCollectId; }
|
||||
public void setDeviceCollectId(long deviceCollectId) { this.deviceCollectId = deviceCollectId; }
|
||||
public String getFirstSuccessTime() { return firstSuccessTime; }
|
||||
public void setFirstSuccessTime(String firstSuccessTime) { this.firstSuccessTime = firstSuccessTime; }
|
||||
public String getLastSuccessTime() { return lastSuccessTime; }
|
||||
public void setLastSuccessTime(String lastSuccessTime) { this.lastSuccessTime = lastSuccessTime; }
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package com.common.service;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.kafka.core.KafkaTemplate;
|
||||
import org.springframework.kafka.support.SendResult;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.concurrent.ListenableFuture;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
* Relays durable outbox events to the dedicated projection topic.
|
||||
*
|
||||
* <p>Multiple application nodes may relay the same row during a race. The consumer's applied-event
|
||||
* table makes that harmless, so the relay never needs a distributed lease that could stall the
|
||||
* fact path.</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class StatsProjectionOutboxRelay {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final KafkaTemplate<String, String> kafkaTemplate;
|
||||
private final AtomicBoolean running = new AtomicBoolean();
|
||||
private final AtomicLong published = new AtomicLong();
|
||||
private final AtomicLong failures = new AtomicLong();
|
||||
private final AtomicLong cleaned = new AtomicLong();
|
||||
private volatile long lastSuccessAt;
|
||||
private volatile long lastFailureAt;
|
||||
|
||||
@Value("${stats.projection-async.enabled:true}") private boolean enabled;
|
||||
@Value("${stats.projection-async.outbox-table:stats_projection_outbox}") private String outboxTable;
|
||||
@Value("${stats.projection-async.applied-table:stats_projection_applied_event}") private String appliedTable;
|
||||
@Value("${stats.projection-async.topic:${spring.kafka.consumer.topic}.STATS.PROJECTION}") private String topic;
|
||||
@Value("${stats.projection-async.relay-batch-size:100}") private int batchSize;
|
||||
@Value("${stats.projection-async.publish-timeout-ms:10000}") private long publishTimeoutMs;
|
||||
@Value("${stats.projection-async.retry-backoff-ms:1000}") private long retryBackoffMs;
|
||||
@Value("${stats.projection-async.redelivery-interval-ms:60000}") private long redeliveryIntervalMs;
|
||||
@Value("${stats.projection-async.retention-days:14}") private int retentionDays;
|
||||
|
||||
public StatsProjectionOutboxRelay(JdbcTemplate jdbc, KafkaTemplate<String, String> kafkaTemplate) {
|
||||
this.jdbc = jdbc;
|
||||
this.kafkaTemplate = kafkaTemplate;
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${stats.projection-async.relay-interval-ms:200}")
|
||||
public void relay() {
|
||||
if (!enabled || !running.compareAndSet(false, true)) return;
|
||||
try {
|
||||
for (OutboxRow row : loadDueRows()) {
|
||||
publish(row);
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
failures.incrementAndGet();
|
||||
lastFailureAt = System.currentTimeMillis();
|
||||
log.error("统计投影 Outbox 扫描失败,下轮自动重试", failure);
|
||||
} finally {
|
||||
running.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
private List<OutboxRow> loadDueRows() {
|
||||
String table = StatsProjectionOutboxWriter.safeTable(outboxTable);
|
||||
String sql = "SELECT event_id,payload FROM (SELECT event_id,payload FROM " + table +
|
||||
" WHERE status IN ('PENDING','FAILED','PUBLISHED') AND (next_attempt_at IS NULL " +
|
||||
"OR next_attempt_at<=SYSDATE) ORDER BY created_at,event_id) WHERE ROWNUM<=?";
|
||||
return jdbc.query(sql, ps -> ps.setInt(1, Math.max(1, batchSize)),
|
||||
(rs, rowNum) -> new OutboxRow(rs.getString(1), rs.getString(2)));
|
||||
}
|
||||
|
||||
private void publish(OutboxRow row) {
|
||||
try {
|
||||
ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(
|
||||
topic, StatsProjectionOutboxEvent.KAFKA_KEY, row.payload);
|
||||
future.get(Math.max(1L, publishTimeoutMs), TimeUnit.MILLISECONDS);
|
||||
jdbc.update("UPDATE " + StatsProjectionOutboxWriter.safeTable(outboxTable) +
|
||||
" SET status='PUBLISHED',published_at=SYSDATE,next_attempt_at=?,last_error=NULL," +
|
||||
"updated_at=SYSDATE WHERE event_id=? AND status<>'APPLIED'",
|
||||
new Timestamp(System.currentTimeMillis() + Math.max(1000L, redeliveryIntervalMs)),
|
||||
row.eventId);
|
||||
published.incrementAndGet();
|
||||
lastSuccessAt = System.currentTimeMillis();
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
markFailure(row, interrupted);
|
||||
} catch (Exception failure) {
|
||||
markFailure(row, failure);
|
||||
}
|
||||
}
|
||||
|
||||
private void markFailure(OutboxRow row, Exception failure) {
|
||||
failures.incrementAndGet();
|
||||
lastFailureAt = System.currentTimeMillis();
|
||||
String message = String.valueOf(failure.getMessage());
|
||||
if (message.length() > 1800) message = message.substring(0, 1800);
|
||||
try {
|
||||
jdbc.update("UPDATE " + StatsProjectionOutboxWriter.safeTable(outboxTable) +
|
||||
" SET status='FAILED',attempt_count=attempt_count+1,next_attempt_at=?," +
|
||||
"last_error=?,updated_at=SYSDATE WHERE event_id=? AND status<>'APPLIED'",
|
||||
new Timestamp(System.currentTimeMillis() + Math.max(0L, retryBackoffMs)),
|
||||
message, row.eventId);
|
||||
} catch (RuntimeException markFailure) {
|
||||
failure.addSuppressed(markFailure);
|
||||
}
|
||||
log.error("统计投影 Outbox 发布失败,将自动重试: eventId={}", row.eventId, failure);
|
||||
}
|
||||
|
||||
@Scheduled(initialDelayString = "${stats.projection-async.cleanup-initial-delay-ms:3600000}",
|
||||
fixedDelayString = "${stats.projection-async.cleanup-interval-ms:3600000}")
|
||||
public void cleanup() {
|
||||
if (!enabled) return;
|
||||
long keepMillis = TimeUnit.DAYS.toMillis(Math.max(1, retentionDays));
|
||||
Timestamp cutoff = new Timestamp(System.currentTimeMillis() - keepMillis);
|
||||
int removed = jdbc.update("DELETE FROM " + StatsProjectionOutboxWriter.safeTable(outboxTable) +
|
||||
" WHERE status='APPLIED' AND applied_at<?", cutoff);
|
||||
removed += jdbc.update("DELETE FROM " + StatsProjectionOutboxWriter.safeTable(appliedTable) +
|
||||
" WHERE applied_at<?", cutoff);
|
||||
cleaned.addAndGet(removed);
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("enabled", enabled);
|
||||
result.put("topic", topic);
|
||||
result.put("running", running.get());
|
||||
result.put("published_total", published.get());
|
||||
result.put("failures_total", failures.get());
|
||||
result.put("cleaned_rows_total", cleaned.get());
|
||||
result.put("last_success_epoch_ms", lastSuccessAt == 0L ? null : lastSuccessAt);
|
||||
result.put("last_failure_epoch_ms", lastFailureAt == 0L ? null : lastFailureAt);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static final class OutboxRow {
|
||||
private final String eventId;
|
||||
private final String payload;
|
||||
private OutboxRow(String eventId, String payload) {
|
||||
this.eventId = eventId;
|
||||
this.payload = payload;
|
||||
}
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/** Writes one aggregated outbox row in the same transaction as the corresponding fact batch. */
|
||||
@Component
|
||||
public class StatsProjectionOutboxWriter {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AtomicLong events = new AtomicLong();
|
||||
private final AtomicLong failures = new AtomicLong();
|
||||
|
||||
@Value("${stats.projection-async.enabled:true}") private boolean enabled;
|
||||
@Value("${stats.projection-async.outbox-table:stats_projection_outbox}") private String outboxTable;
|
||||
|
||||
public StatsProjectionOutboxWriter(JdbcTemplate jdbc, ObjectMapper objectMapper) {
|
||||
this.jdbc = jdbc;
|
||||
this.objectMapper = objectMapper.copy();
|
||||
this.objectMapper.deactivateDefaultTyping();
|
||||
}
|
||||
|
||||
public boolean isEnabled() { return enabled; }
|
||||
|
||||
public int append(StatsProjectionOutboxEvent event) {
|
||||
if (!enabled || event == null || event.isEmpty()) return 0;
|
||||
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
|
||||
throw new IllegalStateException("Stats projection outbox must be written inside a transaction");
|
||||
}
|
||||
event.validate();
|
||||
try {
|
||||
int inserted = jdbc.update("INSERT INTO " + safeTable(outboxTable) +
|
||||
" (event_id,event_schema,payload,status,attempt_count,next_attempt_at," +
|
||||
"created_at,updated_at) VALUES (?,?,?,'PENDING',0,SYSDATE,SYSDATE,SYSDATE)",
|
||||
event.getEventId(), event.getSchema(), objectMapper.writeValueAsString(event));
|
||||
events.incrementAndGet();
|
||||
return inserted;
|
||||
} catch (JsonProcessingException serializationFailure) {
|
||||
failures.incrementAndGet();
|
||||
throw new IllegalStateException("Failed to serialize stats projection outbox event", serializationFailure);
|
||||
} catch (RuntimeException databaseFailure) {
|
||||
failures.incrementAndGet();
|
||||
throw databaseFailure;
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("enabled", enabled);
|
||||
result.put("outbox_table", outboxTable);
|
||||
result.put("events_written_total", events.get());
|
||||
result.put("write_failures_total", failures.get());
|
||||
return result;
|
||||
}
|
||||
|
||||
static String safeTable(String table) {
|
||||
if (table == null || !table.matches("[A-Za-z][A-Za-z0-9_]*")) {
|
||||
throw new IllegalStateException("Invalid stats projection table: " + table);
|
||||
}
|
||||
return table;
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -9,6 +9,7 @@ import com.common.mapper.SyslogNonNormalMessageMapper;
|
||||
import com.common.service.SyslogNonNormalMessageService;
|
||||
import com.common.service.StatsChangeCaptureService;
|
||||
import com.common.service.DirectStatsProjectionWriter;
|
||||
import com.common.service.DmLargeTextLimiter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
@@ -40,13 +41,17 @@ public class SyslogNonNormalMessageServiceImpl
|
||||
@Autowired
|
||||
private DirectStatsProjectionWriter directStatsProjectionWriter;
|
||||
|
||||
@Value("${dm.non-normal-write.batch-size:500}")
|
||||
@Autowired(required = false)
|
||||
private DmLargeTextLimiter largeTextLimiter;
|
||||
|
||||
@Value("${dm.non-normal-write.batch-size:2000}")
|
||||
private int nonNormalBatchSize;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean saveMessage(SyslogNonNormalMessage message) {
|
||||
try {
|
||||
truncateLargeFields(message);
|
||||
// 设置ID(如果未提供)
|
||||
if (message.getId() == null || message.getId().isEmpty()) {
|
||||
message.setId(generateMessageId());
|
||||
@@ -101,6 +106,7 @@ public class SyslogNonNormalMessageServiceImpl
|
||||
try {
|
||||
// 为每条记录设置默认值
|
||||
for (SyslogNonNormalMessage message : messages) {
|
||||
truncateLargeFields(message);
|
||||
if (message.getId() == null || message.getId().isEmpty()) {
|
||||
message.setId(generateMessageId());
|
||||
}
|
||||
@@ -159,10 +165,15 @@ public class SyslogNonNormalMessageServiceImpl
|
||||
}
|
||||
}
|
||||
|
||||
private void truncateLargeFields(SyslogNonNormalMessage message) {
|
||||
if (largeTextLimiter != null) largeTextLimiter.truncateNonNormal(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean updateMessage(SyslogNonNormalMessage message) {
|
||||
try {
|
||||
truncateLargeFields(message);
|
||||
SyslogNonNormalMessage oldValue = getMessageById(message.getId());
|
||||
// 设置更新时间
|
||||
message.setUpdateTime(LocalDateTime.now());
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.common.util;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/** UTF-8 字节预算截断器;标记属于最终存储值的一部分,且永不切断 Unicode 字符。 */
|
||||
public final class Utf8TextTruncator {
|
||||
private static final String MARKER_FORMAT = "...[HB_XDR_TRUNCATED original_utf8_bytes=%d]";
|
||||
|
||||
private Utf8TextTruncator() { }
|
||||
|
||||
public static Result truncate(String text, long maxUtf8Bytes) {
|
||||
if (text == null) return new Result(null, false, 0L, 0L, null);
|
||||
if (maxUtf8Bytes < 0L) throw new IllegalArgumentException("maxUtf8Bytes 不能小于 0");
|
||||
|
||||
byte[] original = text.getBytes(StandardCharsets.UTF_8);
|
||||
long originalBytes = original.length;
|
||||
if (maxUtf8Bytes == 0L || originalBytes <= maxUtf8Bytes) {
|
||||
return new Result(text, false, originalBytes, originalBytes, null);
|
||||
}
|
||||
|
||||
String marker = String.format(MARKER_FORMAT, originalBytes);
|
||||
int markerBytes = marker.getBytes(StandardCharsets.UTF_8).length;
|
||||
if (maxUtf8Bytes < markerBytes) {
|
||||
throw new IllegalArgumentException("UTF-8 截断上限小于截断标记长度: limit="
|
||||
+ maxUtf8Bytes + ", markerBytes=" + markerBytes);
|
||||
}
|
||||
long prefixBudget = maxUtf8Bytes - markerBytes;
|
||||
int end = prefixEnd(text, prefixBudget);
|
||||
String stored = text.substring(0, end) + marker;
|
||||
return new Result(stored, true, originalBytes,
|
||||
stored.getBytes(StandardCharsets.UTF_8).length, sha256(original));
|
||||
}
|
||||
|
||||
private static int prefixEnd(String text, long byteBudget) {
|
||||
long used = 0L;
|
||||
int index = 0;
|
||||
while (index < text.length()) {
|
||||
int codePoint = text.codePointAt(index);
|
||||
int width = utf8Width(codePoint);
|
||||
if (used + width > byteBudget) break;
|
||||
used += width;
|
||||
index += Character.charCount(codePoint);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
private static int utf8Width(int codePoint) {
|
||||
if (codePoint <= 0x7f) return 1;
|
||||
if (codePoint <= 0x7ff) return 2;
|
||||
if (codePoint <= 0xffff) return 3;
|
||||
return 4;
|
||||
}
|
||||
|
||||
private static String sha256(byte[] bytes) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes);
|
||||
StringBuilder hex = new StringBuilder(digest.length * 2);
|
||||
for (byte item : digest) hex.append(String.format("%02x", item & 0xff));
|
||||
return hex.toString();
|
||||
} catch (Exception impossible) {
|
||||
throw new IllegalStateException("JVM 不支持 SHA-256", impossible);
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Result {
|
||||
private final String value;
|
||||
private final boolean truncated;
|
||||
private final long originalUtf8Bytes;
|
||||
private final long storedUtf8Bytes;
|
||||
private final String originalSha256;
|
||||
|
||||
Result(String value, boolean truncated, long originalUtf8Bytes,
|
||||
long storedUtf8Bytes, String originalSha256) {
|
||||
this.value = value;
|
||||
this.truncated = truncated;
|
||||
this.originalUtf8Bytes = originalUtf8Bytes;
|
||||
this.storedUtf8Bytes = storedUtf8Bytes;
|
||||
this.originalSha256 = originalSha256;
|
||||
}
|
||||
|
||||
public String getValue() { return value; }
|
||||
public boolean isTruncated() { return truncated; }
|
||||
public long getOriginalUtf8Bytes() { return originalUtf8Bytes; }
|
||||
public long getStoredUtf8Bytes() { return storedUtf8Bytes; }
|
||||
public String getOriginalSha256() { return originalSha256; }
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,14 @@ public class AppProperties {
|
||||
@Value("${influxdb.connection.write-timeout:60s}")
|
||||
private Duration influxWriteTimeout;
|
||||
|
||||
/** 原文写请求的单阶段上限;避免 InfluxDB 变慢长期占住 Kafka listener。 */
|
||||
@Value("${influxdb.raw.write-request-timeout:5s}")
|
||||
private Duration influxRawWriteRequestTimeout;
|
||||
|
||||
/** 原文写失败后的快速失败时间,期间不再向故障 InfluxDB 发起请求。 */
|
||||
@Value("${influxdb.raw.failure-backoff-ms:30000}")
|
||||
private long influxRawFailureBackoffMs;
|
||||
|
||||
// ========== 应用配置 ==========
|
||||
@Value("${app.worker.threads:4}")
|
||||
private int workerThreads;
|
||||
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package com.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
/** Kafka 积压期间的可审计降级采样配置。 */
|
||||
@Component
|
||||
public class BacklogSamplingProperties {
|
||||
|
||||
public static final int BASIS_POINTS = 10_000;
|
||||
|
||||
@Value("${syslog.backlog-sampling.enabled:true}")
|
||||
private boolean enabled;
|
||||
|
||||
@Value("${syslog.backlog-sampling.lag-threshold-ms:3600000}")
|
||||
private long lagThresholdMs;
|
||||
|
||||
@Value("${syslog.backlog-sampling.start-lag-ms:900000}")
|
||||
private long startLagMs;
|
||||
|
||||
@Value("${syslog.backlog-sampling.normal-retain-bps:1000}")
|
||||
private int normalRetainBps;
|
||||
|
||||
@Value("${syslog.backlog-sampling.non-normal-retain-bps:2000}")
|
||||
private int nonNormalRetainBps;
|
||||
|
||||
@Value("${syslog.backlog-sampling.degrade-steps:10}")
|
||||
private int degradeSteps;
|
||||
|
||||
@Value("${syslog.backlog-sampling.policy-version:v2}")
|
||||
private String policyVersion;
|
||||
|
||||
@Value("${syslog.backlog-sampling.audit-timeout-seconds:5}")
|
||||
private int auditTimeoutSeconds;
|
||||
|
||||
@Value("${syslog.backlog-sampling.audit-retry-backoff-ms:60000}")
|
||||
private long auditRetryBackoffMs;
|
||||
|
||||
@PostConstruct
|
||||
public void validate() {
|
||||
if (lagThresholdMs < 1L) {
|
||||
throw new IllegalArgumentException("syslog.backlog-sampling.lag-threshold-ms 必须大于 0");
|
||||
}
|
||||
if (startLagMs < 0L || startLagMs >= lagThresholdMs) {
|
||||
throw new IllegalArgumentException("syslog.backlog-sampling.start-lag-ms 必须大于等于 0,且小于 lag-threshold-ms");
|
||||
}
|
||||
validateRate("normal-retain-bps", normalRetainBps);
|
||||
validateRate("non-normal-retain-bps", nonNormalRetainBps);
|
||||
if (degradeSteps < 1 || degradeSteps > 1000) {
|
||||
throw new IllegalArgumentException("syslog.backlog-sampling.degrade-steps 必须在 1~1000 之间");
|
||||
}
|
||||
if (policyVersion == null || policyVersion.trim().isEmpty() || policyVersion.length() > 64) {
|
||||
throw new IllegalArgumentException("syslog.backlog-sampling.policy-version 必须为 1~64 个字符");
|
||||
}
|
||||
if (auditTimeoutSeconds < 1) {
|
||||
throw new IllegalArgumentException("syslog.backlog-sampling.audit-timeout-seconds 必须大于 0");
|
||||
}
|
||||
if (auditRetryBackoffMs < 1L) {
|
||||
throw new IllegalArgumentException("syslog.backlog-sampling.audit-retry-backoff-ms 必须大于 0");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateRate(String name, int value) {
|
||||
if (value < 0 || value > BASIS_POINTS) {
|
||||
throw new IllegalArgumentException("syslog.backlog-sampling." + name + " 必须在 0~10000 之间");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public long getLagThresholdMs() { return lagThresholdMs; }
|
||||
public long getStartLagMs() { return startLagMs; }
|
||||
public int getNormalRetainBps() { return normalRetainBps; }
|
||||
public int getNonNormalRetainBps() { return nonNormalRetainBps; }
|
||||
public int getDegradeSteps() { return degradeSteps; }
|
||||
public String getPolicyVersion() { return policyVersion; }
|
||||
public int getAuditTimeoutSeconds() { return auditTimeoutSeconds; }
|
||||
public long getAuditRetryBackoffMs() { return auditRetryBackoffMs; }
|
||||
}
|
||||
+112
-4
@@ -1,17 +1,25 @@
|
||||
package com.config;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
import org.springframework.boot.autoconfigure.kafka.ConcurrentKafkaListenerContainerFactoryConfigurer;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
|
||||
import org.springframework.kafka.core.ConsumerFactory;
|
||||
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
|
||||
import org.springframework.kafka.listener.ContainerProperties;
|
||||
import org.springframework.kafka.listener.DefaultErrorHandler;
|
||||
import org.springframework.util.backoff.FixedBackOff;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/** Kafka 消费失败边界:业务未确认的消息绝不能被框架默认恢复器静默跳过。 */
|
||||
@Configuration
|
||||
@Slf4j
|
||||
public class KafkaReliabilityConfig {
|
||||
|
||||
@Bean
|
||||
@@ -28,7 +36,11 @@ public class KafkaReliabilityConfig {
|
||||
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
|
||||
ConsumerFactory<Object, Object> consumerFactory,
|
||||
DefaultErrorHandler syslogDefaultErrorHandler) {
|
||||
return configuredFactory(configurer, consumerFactory, syslogDefaultErrorHandler);
|
||||
ConcurrentKafkaListenerContainerFactory<Object, Object> factory =
|
||||
configuredFactory(configurer, consumerFactory, syslogDefaultErrorHandler);
|
||||
// 默认工厂承载普通 Retry/Replay listener,同样需要让 acknowledge() 覆盖真实提交耗时。
|
||||
factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
|
||||
return factory;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -40,13 +52,94 @@ public class KafkaReliabilityConfig {
|
||||
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
|
||||
ConsumerFactory<Object, Object> consumerFactory,
|
||||
DefaultErrorHandler syslogDefaultErrorHandler,
|
||||
@Value("${syslog.raw-listener.concurrency:3}") int concurrency) {
|
||||
@Value("${syslog.raw-listener.concurrency:3}") int concurrency,
|
||||
@Value("${syslog.raw-listener.max-poll-records:3000}") int baseRecords,
|
||||
@Value("${syslog.raw-listener.adaptive-max-records:5000}") int maxPollRecords) {
|
||||
if (concurrency < 1) {
|
||||
throw new IllegalArgumentException("syslog.raw-listener.concurrency 必须大于 0");
|
||||
}
|
||||
ConcurrentKafkaListenerContainerFactory<Object, Object> factory =
|
||||
configuredFactory(configurer, consumerFactory, syslogDefaultErrorHandler);
|
||||
new com.Modules.NormalData.AdaptiveRawBatchSizer(baseRecords, maxPollRecords);
|
||||
Map<String, Object> properties = new HashMap<>(consumerFactory.getConfigurationProperties());
|
||||
properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords);
|
||||
// 只在所有业务子块完成后手动提交本次poll,禁止自动提交尚未处理的尾部记录。
|
||||
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
|
||||
ConcurrentKafkaListenerContainerFactory<Object, Object> factory = configuredFactory(
|
||||
configurer, new DefaultKafkaConsumerFactory<>(properties), syslogDefaultErrorHandler);
|
||||
factory.setConcurrency(concurrency);
|
||||
// 在 listener 线程调用 acknowledge() 时立即同步提交,使慢批次日志能够准确覆盖
|
||||
// “业务处理完成 -> Kafka offset 提交完成”的全部时间;可靠性语义仍是处理成功后提交。
|
||||
factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
|
||||
log.info("Raw Kafka batch configuration: maxPollRecords={}, baseProcessingRecords={}, "
|
||||
+ "adaptiveMaxRecords={}, concurrency={}",
|
||||
maxPollRecords, baseRecords, maxPollRecords, concurrency);
|
||||
return factory;
|
||||
}
|
||||
|
||||
/** 大日志使用独立 ConsumerFactory,限制单次 poll 条数并显式放开单条拉取上限。 */
|
||||
@Bean("largeRawKafkaListenerContainerFactory")
|
||||
public ConcurrentKafkaListenerContainerFactory<Object, Object> largeRawKafkaListenerContainerFactory(
|
||||
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
|
||||
ConsumerFactory<Object, Object> consumerFactory,
|
||||
DefaultErrorHandler syslogDefaultErrorHandler,
|
||||
@Value("${syslog.large-listener.concurrency:1}") int concurrency,
|
||||
@Value("${syslog.large-listener.max-poll-records:5}") int maxPollRecords,
|
||||
@Value("${syslog.large-listener.max-partition-fetch-bytes:33554432}") int maxPartitionFetchBytes,
|
||||
@Value("${syslog.large-listener.fetch-max-bytes:67108864}") int fetchMaxBytes) {
|
||||
if (concurrency < 1 || maxPollRecords < 1 || maxPartitionFetchBytes < 1
|
||||
|| fetchMaxBytes < maxPartitionFetchBytes) {
|
||||
throw new IllegalArgumentException("大日志 Kafka 并发、poll 和 fetch 参数非法");
|
||||
}
|
||||
Map<String, Object> properties = new HashMap<>(consumerFactory.getConfigurationProperties());
|
||||
properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords);
|
||||
properties.put(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, maxPartitionFetchBytes);
|
||||
properties.put(ConsumerConfig.FETCH_MAX_BYTES_CONFIG, fetchMaxBytes);
|
||||
DefaultKafkaConsumerFactory<Object, Object> largeConsumerFactory =
|
||||
new DefaultKafkaConsumerFactory<>(properties);
|
||||
ConcurrentKafkaListenerContainerFactory<Object, Object> factory =
|
||||
configuredFactory(configurer, largeConsumerFactory, syslogDefaultErrorHandler);
|
||||
factory.setConcurrency(concurrency);
|
||||
factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
|
||||
return factory;
|
||||
}
|
||||
|
||||
/** 统计脏键与原始日志隔离;同一维度 key 由 Kafka 分区保证只被一个组成员处理。 */
|
||||
@Bean("ingressStatsKafkaListenerContainerFactory")
|
||||
public ConcurrentKafkaListenerContainerFactory<Object, Object> ingressStatsKafkaListenerContainerFactory(
|
||||
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
|
||||
ConsumerFactory<Object, Object> consumerFactory,
|
||||
DefaultErrorHandler syslogDefaultErrorHandler,
|
||||
@Value("${stats.ingress-metadata.max-poll-records:2000}") int maxPollRecords,
|
||||
@Value("${stats.ingress-metadata.auto-offset-reset:earliest}") String reset) {
|
||||
return ingressFactory(configurer, consumerFactory, syslogDefaultErrorHandler, maxPollRecords, reset);
|
||||
}
|
||||
|
||||
@Bean("largeIngressStatsKafkaListenerContainerFactory")
|
||||
public ConcurrentKafkaListenerContainerFactory<Object, Object> largeIngressStatsKafkaListenerContainerFactory(
|
||||
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
|
||||
ConsumerFactory<Object, Object> consumerFactory,
|
||||
DefaultErrorHandler syslogDefaultErrorHandler,
|
||||
@Value("${stats.ingress-metadata.auto-offset-reset:earliest}") String reset) {
|
||||
return ingressFactory(configurer, consumerFactory, syslogDefaultErrorHandler, 5, reset);
|
||||
}
|
||||
|
||||
private ConcurrentKafkaListenerContainerFactory<Object, Object> ingressFactory(
|
||||
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
|
||||
ConsumerFactory<Object, Object> source, DefaultErrorHandler errorHandler,
|
||||
int maxPollRecords, String reset) {
|
||||
if (maxPollRecords < 1 || !("earliest".equals(reset) || "latest".equals(reset))) {
|
||||
throw new IllegalArgumentException("入口统计 poll/reset 配置非法");
|
||||
}
|
||||
Map<String, Object> properties = new HashMap<>(source.getConfigurationProperties());
|
||||
properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords);
|
||||
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
|
||||
properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, reset);
|
||||
properties.put(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, 33554432);
|
||||
properties.put(ConsumerConfig.FETCH_MAX_BYTES_CONFIG, 67108864);
|
||||
ConcurrentKafkaListenerContainerFactory<Object, Object> factory = configuredFactory(
|
||||
configurer, new DefaultKafkaConsumerFactory<>(properties), errorHandler);
|
||||
factory.setBatchListener(true);
|
||||
factory.setConcurrency(1);
|
||||
factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
|
||||
return factory;
|
||||
}
|
||||
|
||||
@@ -66,6 +159,21 @@ public class KafkaReliabilityConfig {
|
||||
return factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Projection deltas intentionally use one consumer per instance. All events use one Kafka key,
|
||||
* so only one group member owns the active partition and daily projection rows cannot deadlock.
|
||||
*/
|
||||
@Bean("statsProjectionKafkaListenerContainerFactory")
|
||||
public ConcurrentKafkaListenerContainerFactory<Object, Object> statsProjectionKafkaListenerContainerFactory(
|
||||
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
|
||||
ConsumerFactory<Object, Object> consumerFactory,
|
||||
DefaultErrorHandler syslogDefaultErrorHandler) {
|
||||
ConcurrentKafkaListenerContainerFactory<Object, Object> factory =
|
||||
configuredFactory(configurer, consumerFactory, syslogDefaultErrorHandler);
|
||||
factory.setConcurrency(1);
|
||||
return factory;
|
||||
}
|
||||
|
||||
private ConcurrentKafkaListenerContainerFactory<Object, Object> configuredFactory(
|
||||
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
|
||||
ConsumerFactory<Object, Object> consumerFactory,
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.config;
|
||||
|
||||
import com.Modules.NormalData.cache.NormalizationCompiledCacheInvalidationBus;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.listener.ChannelTopic;
|
||||
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
|
||||
|
||||
/** 规则编译缓存的跨实例失效广播通道。 */
|
||||
@Configuration
|
||||
public class NormalizationCacheInvalidationRedisConfig {
|
||||
|
||||
@Bean
|
||||
public RedisMessageListenerContainer normalizationCacheInvalidationListenerContainer(
|
||||
RedisConnectionFactory connectionFactory,
|
||||
NormalizationCompiledCacheInvalidationBus listener) {
|
||||
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
|
||||
container.setConnectionFactory(connectionFactory);
|
||||
container.addMessageListener(listener,
|
||||
new ChannelTopic(NormalizationCompiledCacheInvalidationBus.TOPIC));
|
||||
return container;
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** 标识运行代码的功能修订;不依赖构建插件、镜像标签或可覆盖的配置版本号。 */
|
||||
@Slf4j
|
||||
@Component
|
||||
public class SyslogBuildStartupLogger {
|
||||
|
||||
// 确认包含此功能修订,不代表唯一构建;后续功能修订时同步更新此标识。
|
||||
static final String CODE_REVISION = "ASYNC_STATS_ADAPTIVE_RAW_V20260917_63";
|
||||
private final Environment environment;
|
||||
|
||||
public SyslogBuildStartupLogger(Environment environment) {
|
||||
this.environment = environment;
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void onApplicationReady() {
|
||||
log.info("[SYSLOG_BUILD_READY] {}", startupSummary());
|
||||
}
|
||||
|
||||
String startupSummary() {
|
||||
return "codeRevision=" + CODE_REVISION
|
||||
+ ", application=syslog-consumer-rule"
|
||||
+ ", profiles=" + String.join(",", environment.getActiveProfiles())
|
||||
+ ", rawEnabled=" + value("syslog.raw-consumer.enabled", "true")
|
||||
+ ", rawConcurrency=" + value("syslog.raw-listener.concurrency", "3")
|
||||
+ ", baseProcessingRecords=" + value("syslog.raw-listener.max-poll-records", "3000")
|
||||
+ ", adaptiveMaxRecords=" + value("syslog.raw-listener.adaptive-max-records", "5000")
|
||||
+ ", dmStandardizedBatchSize=" + value("dm.standardized-write.batch-size", "2000")
|
||||
+ ", dmNonNormalBatchSize=" + value("dm.non-normal-write.batch-size", "2000")
|
||||
+ ", rawFieldMaxUtf8Bytes=" + value("syslog.raw-listener.field-max-utf8-bytes", "2048")
|
||||
+ ", samplingEnabled=" + value("syslog.backlog-sampling.enabled", "true")
|
||||
+ ", statsWriteMode=" + value("stats.write-mode", "DIRECT")
|
||||
+ ", ingressStatsEnabled=" + value("stats.ingress-metadata.enabled", "true")
|
||||
+ ", statsPublisherEnabled=" + value("stats.projection-async.enabled", "true")
|
||||
+ ", lateBucketEnabled=" + value("analysis.late-replay.outbox-enabled", "true")
|
||||
+ ", slowBatchThresholdMs=" + value("syslog.slow-batch.threshold-ms", "1000");
|
||||
}
|
||||
|
||||
private String value(String key, String fallback) {
|
||||
return environment.getProperty(key, fallback);
|
||||
}
|
||||
}
|
||||
+28
@@ -25,6 +25,15 @@ public class ThreadPoolConfig {
|
||||
@Value("${app.processor.thread-pool.keep-alive-seconds:60}")
|
||||
private int keepAliveSeconds;
|
||||
|
||||
@Value("${syslog.large-processor.thread-pool.core-pool-size:1}")
|
||||
private int largeCorePoolSize;
|
||||
|
||||
@Value("${syslog.large-processor.thread-pool.max-pool-size:2}")
|
||||
private int largeMaxPoolSize;
|
||||
|
||||
@Value("${syslog.large-processor.thread-pool.queue-capacity:10}")
|
||||
private int largeQueueCapacity;
|
||||
|
||||
@Value("${dm.standardized-write.writer-concurrency:2}")
|
||||
private int dmWriterConcurrency;
|
||||
|
||||
@@ -54,6 +63,25 @@ public class ThreadPoolConfig {
|
||||
return executor;
|
||||
}
|
||||
|
||||
/** 大日志解析/规则计算独立线程池,避免占满普通日志的计算线程与任务队列。 */
|
||||
@Bean("largeLogProcessorExecutor")
|
||||
public Executor largeLogProcessorExecutor() {
|
||||
if (largeCorePoolSize < 1 || largeMaxPoolSize < largeCorePoolSize || largeQueueCapacity < 1) {
|
||||
throw new IllegalArgumentException("大日志处理线程池参数非法");
|
||||
}
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(largeCorePoolSize);
|
||||
executor.setMaxPoolSize(largeMaxPoolSize);
|
||||
executor.setQueueCapacity(largeQueueCapacity);
|
||||
executor.setKeepAliveSeconds(keepAliveSeconds);
|
||||
executor.setThreadNamePrefix("large-log-processor-");
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
|
||||
executor.setWaitForTasksToCompleteOnShutdown(true);
|
||||
executor.setAwaitTerminationSeconds(60);
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 达梦批写使用独立的有界线程池,不能复用规则计算线程池。
|
||||
*
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.controllers;
|
||||
|
||||
import com.common.service.BacklogSamplingMetrics;
|
||||
import com.config.BacklogSamplingProperties;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/syslog/backlog-sampling")
|
||||
public class BacklogSamplingController {
|
||||
private final BacklogSamplingProperties properties;
|
||||
private final BacklogSamplingMetrics metrics;
|
||||
private final com.common.service.BacklogSamplingAuditService auditService;
|
||||
|
||||
public BacklogSamplingController(BacklogSamplingProperties properties,
|
||||
BacklogSamplingMetrics metrics,
|
||||
com.common.service.BacklogSamplingAuditService auditService) {
|
||||
this.properties = properties;
|
||||
this.metrics = metrics;
|
||||
this.auditService = auditService;
|
||||
}
|
||||
|
||||
@GetMapping("/status")
|
||||
public Map<String, Object> status() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("enabled", properties.isEnabled());
|
||||
result.put("start_lag_ms", properties.getStartLagMs());
|
||||
result.put("lag_threshold_ms", properties.getLagThresholdMs());
|
||||
result.put("normal_retain_bps", properties.getNormalRetainBps());
|
||||
result.put("non_normal_retain_bps", properties.getNonNormalRetainBps());
|
||||
result.put("degrade_steps", properties.getDegradeSteps());
|
||||
result.put("policy_version", properties.getPolicyVersion());
|
||||
result.putAll(metrics.snapshot());
|
||||
result.put("audit_async", auditService.status());
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+16
-1
@@ -7,6 +7,9 @@ import com.common.service.DmStandardizedBatchExecutor;
|
||||
import com.common.service.StatsMaterializationConsumer;
|
||||
import com.common.service.StatsMaterializationPublisher;
|
||||
import com.common.service.StatsMaterializationReconciler;
|
||||
import com.common.service.StatsProjectionOutboxWriter;
|
||||
import com.common.service.StatsProjectionOutboxRelay;
|
||||
import com.common.service.StatsProjectionDeltaConsumer;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -25,6 +28,9 @@ public class DirectStatsController {
|
||||
private final StatsMaterializationPublisher materializationPublisher;
|
||||
private final StatsMaterializationConsumer materializationConsumer;
|
||||
private final StatsMaterializationReconciler materializationReconciler;
|
||||
private final StatsProjectionOutboxWriter projectionOutboxWriter;
|
||||
private final StatsProjectionOutboxRelay projectionOutboxRelay;
|
||||
private final StatsProjectionDeltaConsumer projectionDeltaConsumer;
|
||||
|
||||
public DirectStatsController(DirectStatsProjectionWriter writer,
|
||||
IngressStatsProjectionWriter ingressWriter,
|
||||
@@ -32,7 +38,10 @@ public class DirectStatsController {
|
||||
DmStandardizedBatchExecutor batchExecutor,
|
||||
StatsMaterializationPublisher materializationPublisher,
|
||||
StatsMaterializationConsumer materializationConsumer,
|
||||
StatsMaterializationReconciler materializationReconciler) {
|
||||
StatsMaterializationReconciler materializationReconciler,
|
||||
StatsProjectionOutboxWriter projectionOutboxWriter,
|
||||
StatsProjectionOutboxRelay projectionOutboxRelay,
|
||||
StatsProjectionDeltaConsumer projectionDeltaConsumer) {
|
||||
this.writer = writer;
|
||||
this.ingressWriter = ingressWriter;
|
||||
this.dayRolloverService = dayRolloverService;
|
||||
@@ -40,6 +49,9 @@ public class DirectStatsController {
|
||||
this.materializationPublisher = materializationPublisher;
|
||||
this.materializationConsumer = materializationConsumer;
|
||||
this.materializationReconciler = materializationReconciler;
|
||||
this.projectionOutboxWriter = projectionOutboxWriter;
|
||||
this.projectionOutboxRelay = projectionOutboxRelay;
|
||||
this.projectionDeltaConsumer = projectionDeltaConsumer;
|
||||
}
|
||||
|
||||
@GetMapping("/status")
|
||||
@@ -51,6 +63,9 @@ public class DirectStatsController {
|
||||
status.put("materialization_publisher", materializationPublisher.status());
|
||||
status.put("materialization_consumer", materializationConsumer.status());
|
||||
status.put("materialization_reconciler", materializationReconciler.status());
|
||||
status.put("projection_outbox_writer", projectionOutboxWriter.status());
|
||||
status.put("projection_outbox_relay", projectionOutboxRelay.status());
|
||||
status.put("projection_delta_consumer", projectionDeltaConsumer.status());
|
||||
return ResponseEntity.ok(status);
|
||||
}
|
||||
}
|
||||
|
||||
+7
-2
@@ -1,6 +1,7 @@
|
||||
package com.controllers;
|
||||
|
||||
import com.common.service.IngressStatsProjectionWriter;
|
||||
import com.common.service.IngressStatsConsumer;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -13,13 +14,17 @@ import java.util.Map;
|
||||
@RequestMapping("/api/syslog/stats/ingress")
|
||||
public class IngressStatsController {
|
||||
private final IngressStatsProjectionWriter writer;
|
||||
private final IngressStatsConsumer consumer;
|
||||
|
||||
public IngressStatsController(IngressStatsProjectionWriter writer) {
|
||||
public IngressStatsController(IngressStatsProjectionWriter writer, IngressStatsConsumer consumer) {
|
||||
this.writer = writer;
|
||||
this.consumer = consumer;
|
||||
}
|
||||
|
||||
@GetMapping("/status")
|
||||
public ResponseEntity<Map<String, Object>> status() {
|
||||
return ResponseEntity.ok(writer.status());
|
||||
Map<String, Object> result = writer.status();
|
||||
result.put("consumer", consumer.status());
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.controllers;
|
||||
|
||||
import com.Modules.NormalData.cache.NormalizationRuleCacheManagementService;
|
||||
import com.Modules.NormalData.cache.NormalizationRuleCacheManagementService.ClearResult;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** 只清理标准化规则相关缓存,不执行现有 /api/cache/all 的全 Redis 删除。 */
|
||||
@RestController
|
||||
@RequestMapping("/api/syslog/normalization/cache")
|
||||
public class NormalizationRuleCacheController {
|
||||
private final NormalizationRuleCacheManagementService service;
|
||||
|
||||
public NormalizationRuleCacheController(NormalizationRuleCacheManagementService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@DeleteMapping("/devices/{deviceId}")
|
||||
public ResponseEntity<Map<String, Object>> clearDevice(@PathVariable Long deviceId) {
|
||||
if (deviceId == null || deviceId <= 0L) {
|
||||
Map<String, Object> error = new LinkedHashMap<>();
|
||||
error.put("cleared", false);
|
||||
error.put("errorCode", "INVALID_DEVICE_ID");
|
||||
error.put("message", "deviceId 必须大于 0");
|
||||
return ResponseEntity.badRequest().body(error);
|
||||
}
|
||||
return ResponseEntity.ok(response(service.clearDevice(deviceId)));
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
public Map<String, Object> clearAll() {
|
||||
return response(service.clearAll());
|
||||
}
|
||||
|
||||
private Map<String, Object> response(ClearResult result) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("cleared", true);
|
||||
body.put("scope", result.getScope());
|
||||
if (result.getDeviceId() != null) body.put("deviceId", result.getDeviceId());
|
||||
body.put("deviceCount", result.getDeviceCount());
|
||||
if (result.getDeviceId() != null) {
|
||||
body.put("associatedRuleCount", result.getAssociatedRuleCount());
|
||||
}
|
||||
return body;
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.controllers;
|
||||
|
||||
import com.common.service.RawLogCaptureService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Max;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.net.URI;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
/** 现场按设备开启短时间、异常优先的原始日志采样。 */
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/api/syslog/raw-captures")
|
||||
public class RawLogCaptureController {
|
||||
|
||||
private final RawLogCaptureService captureService;
|
||||
|
||||
public RawLogCaptureController(RawLogCaptureService captureService) {
|
||||
this.captureService = captureService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<RawLogCaptureService.CaptureSnapshot> start(
|
||||
@Valid @RequestBody StartCaptureRequest request) {
|
||||
RawLogCaptureService.CaptureSnapshot snapshot = captureService.start(
|
||||
request.getDeviceId(), request.getDurationSeconds(), request.getMessageCount());
|
||||
return ResponseEntity.accepted()
|
||||
.location(URI.create("/api/syslog/raw-captures/" + snapshot.getSessionId()))
|
||||
.body(snapshot);
|
||||
}
|
||||
|
||||
@GetMapping("/{sessionId}")
|
||||
public ResponseEntity<RawLogCaptureService.CaptureSnapshot> get(
|
||||
@PathVariable String sessionId) {
|
||||
RawLogCaptureService.CaptureSnapshot snapshot = captureService.get(sessionId);
|
||||
return snapshot == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(snapshot);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{sessionId}")
|
||||
public ResponseEntity<RawLogCaptureService.CaptureSnapshot> stop(
|
||||
@PathVariable String sessionId) {
|
||||
RawLogCaptureService.CaptureSnapshot snapshot = captureService.stop(sessionId);
|
||||
return snapshot == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(snapshot);
|
||||
}
|
||||
|
||||
@ExceptionHandler(RawLogCaptureService.CaptureDisabledException.class)
|
||||
public ResponseEntity<Map<String, String>> disabled(
|
||||
RawLogCaptureService.CaptureDisabledException failure) {
|
||||
return ResponseEntity.status(503)
|
||||
.body(Collections.singletonMap("message", failure.getMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(RawLogCaptureService.CaptureCapacityException.class)
|
||||
public ResponseEntity<Map<String, String>> capacity(
|
||||
RawLogCaptureService.CaptureCapacityException failure) {
|
||||
return ResponseEntity.status(429)
|
||||
.body(Collections.singletonMap("message", failure.getMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(RawLogCaptureService.CaptureCoordinationException.class)
|
||||
public ResponseEntity<Map<String, String>> coordination(
|
||||
RawLogCaptureService.CaptureCoordinationException failure) {
|
||||
return ResponseEntity.status(503)
|
||||
.body(Collections.singletonMap("message", failure.getMessage()));
|
||||
}
|
||||
|
||||
public static final class StartCaptureRequest {
|
||||
@NotNull(message = "deviceId 不能为空")
|
||||
@Min(value = 1, message = "deviceId 必须大于 0")
|
||||
private Long deviceId;
|
||||
|
||||
@NotNull(message = "durationSeconds 不能为空")
|
||||
@Min(value = 1, message = "durationSeconds 最小为 1")
|
||||
@Max(value = RawLogCaptureService.MAX_DURATION_SECONDS,
|
||||
message = "durationSeconds 不能超过 600")
|
||||
private Integer durationSeconds;
|
||||
|
||||
@NotNull(message = "messageCount 不能为空")
|
||||
@Min(value = 1, message = "messageCount 最小为 1")
|
||||
@Max(value = RawLogCaptureService.MAX_MESSAGE_COUNT,
|
||||
message = "messageCount 不能超过 50")
|
||||
private Integer messageCount;
|
||||
|
||||
public Long getDeviceId() { return deviceId; }
|
||||
public void setDeviceId(Long deviceId) { this.deviceId = deviceId; }
|
||||
public Integer getDurationSeconds() { return durationSeconds; }
|
||||
public void setDurationSeconds(Integer durationSeconds) { this.durationSeconds = durationSeconds; }
|
||||
public Integer getMessageCount() { return messageCount; }
|
||||
public void setMessageCount(Integer messageCount) { this.messageCount = messageCount; }
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.controllers;
|
||||
|
||||
import com.common.service.DmLargeTextLimiter;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** 大字段截断观测,指标只包含计数,不暴露设备原文。 */
|
||||
@RestController
|
||||
@RequestMapping("/api/syslog/storage-limits")
|
||||
public class StorageLimitMetricsController {
|
||||
private final DmLargeTextLimiter limiter;
|
||||
|
||||
public StorageLimitMetricsController(DmLargeTextLimiter limiter) { this.limiter = limiter; }
|
||||
|
||||
@GetMapping("/metrics")
|
||||
public Map<String, Long> metrics() {
|
||||
Map<String, Long> values = new LinkedHashMap<>();
|
||||
values.put("dm_normal_fields_truncated_total", limiter.getNormalFieldsTruncated());
|
||||
values.put("dm_non_normal_fields_truncated_total", limiter.getNonNormalFieldsTruncated());
|
||||
return values;
|
||||
}
|
||||
}
|
||||
+54
-4
@@ -5,6 +5,7 @@ import com.influxdb.client.InfluxDBClientOptions;
|
||||
import com.influxdb.client.WriteApi;
|
||||
import com.influxdb.client.WriteApiBlocking;
|
||||
import com.influxdb.client.domain.HealthCheck;
|
||||
import com.influxdb.exceptions.BadRequestException;
|
||||
import com.influxdb.client.write.Point;
|
||||
import com.config.AppProperties;
|
||||
import org.slf4j.Logger;
|
||||
@@ -17,6 +18,8 @@ import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import com.influxdb.client.QueryApi;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@@ -41,6 +44,9 @@ public class InfluxDBClient implements AutoCloseable {
|
||||
|
||||
private final InfluxDBConfig influxDBConfig;
|
||||
private final RawStorageProperties rawStorage;
|
||||
private final long rawWriteFailureBackoffMs;
|
||||
private final AtomicInteger consecutiveRawWriteFailures = new AtomicInteger();
|
||||
private volatile long rawWriteRetryAfterMs;
|
||||
|
||||
@Autowired
|
||||
public InfluxDBClient(AppProperties appProperties, InfluxDBConfig influxDBConfig,
|
||||
@@ -48,10 +54,21 @@ public class InfluxDBClient implements AutoCloseable {
|
||||
this.influxDBConfig = influxDBConfig;
|
||||
this.rawStorage = rawStorage;
|
||||
|
||||
final int rawWriteTimeoutMs = durationMillisAsInt(appProperties.getInfluxRawWriteRequestTimeout());
|
||||
this.rawWriteFailureBackoffMs = Math.max(1L, appProperties.getInfluxRawFailureBackoffMs());
|
||||
OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
|
||||
.connectTimeout(appProperties.getInfluxConnectionTimeout())
|
||||
.readTimeout(appProperties.getInfluxReadTimeout())
|
||||
.writeTimeout(appProperties.getInfluxWriteTimeout());
|
||||
.writeTimeout(appProperties.getInfluxWriteTimeout())
|
||||
.addInterceptor(chain -> {
|
||||
if ("/api/v2/write".equals(chain.request().url().encodedPath())) {
|
||||
return chain.withConnectTimeout(rawWriteTimeoutMs, TimeUnit.MILLISECONDS)
|
||||
.withReadTimeout(rawWriteTimeoutMs, TimeUnit.MILLISECONDS)
|
||||
.withWriteTimeout(rawWriteTimeoutMs, TimeUnit.MILLISECONDS)
|
||||
.proceed(chain.request());
|
||||
}
|
||||
return chain.proceed(chain.request());
|
||||
});
|
||||
InfluxDBClientOptions options = InfluxDBClientOptions.builder()
|
||||
.url(appProperties.getInfluxUrl())
|
||||
.authenticateToken(appProperties.getInfluxToken().toCharArray())
|
||||
@@ -79,8 +96,9 @@ public class InfluxDBClient implements AutoCloseable {
|
||||
logger.warn("InfluxDB health check: {}", health.getMessage());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to connect to InfluxDB: {}", e.getMessage());
|
||||
throw new RuntimeException("InfluxDB connection failed", e);
|
||||
// 原文存储是旁路依赖。启动时不可用不能阻止 Kafka 消费和告警入库。
|
||||
logger.error("[INFLUX_NON_BLOCKING] InfluxDB 启动健康检查失败,消费者仍将启动: {}",
|
||||
e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,9 +123,12 @@ public class InfluxDBClient implements AutoCloseable {
|
||||
}
|
||||
|
||||
public void writePointBlocking(String targetBucket, Point point) {
|
||||
ensureRawWriteAvailable();
|
||||
try {
|
||||
writeApiBlocking.writePoint(targetBucket, org, point);
|
||||
recordRawWriteSuccess();
|
||||
} catch (Exception e) {
|
||||
recordRawWriteFailure(e);
|
||||
logger.error("Failed to write point to InfluxDB (blocking): {}", e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
@@ -116,7 +137,7 @@ public class InfluxDBClient implements AutoCloseable {
|
||||
|
||||
/**
|
||||
* 批量同步写入原始日志点。
|
||||
* 调用返回表示 InfluxDB 已确认整批写入;任何异常都会上抛到 Kafka ACK 边界。
|
||||
* 调用返回表示 InfluxDB 已确认整批写入;任何异常都会上抛给主流程的非阻塞旁路边界。
|
||||
*/
|
||||
public void writePointsBlocking(List<Point> points) {
|
||||
writePointsBlocking(bucket, points);
|
||||
@@ -126,15 +147,44 @@ public class InfluxDBClient implements AutoCloseable {
|
||||
if (points == null || points.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
ensureRawWriteAvailable();
|
||||
try {
|
||||
writeApiBlocking.writePoints(targetBucket, org, points);
|
||||
recordRawWriteSuccess();
|
||||
} catch (Exception e) {
|
||||
recordRawWriteFailure(e);
|
||||
logger.error("Failed to write {} points to InfluxDB (blocking batch): {}",
|
||||
points.size(), e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureRawWriteAvailable() {
|
||||
long remainingMs = rawWriteRetryAfterMs - System.currentTimeMillis();
|
||||
if (remainingMs > 0L) {
|
||||
throw new IllegalStateException("InfluxDB 原文写入熔断中,剩余 " + remainingMs + "ms");
|
||||
}
|
||||
}
|
||||
|
||||
private void recordRawWriteSuccess() {
|
||||
consecutiveRawWriteFailures.set(0);
|
||||
rawWriteRetryAfterMs = 0L;
|
||||
}
|
||||
|
||||
private void recordRawWriteFailure(Exception failure) {
|
||||
// 400 是当前数据格式问题,外层会逐条隔离,不代表 InfluxDB 整体不可用。
|
||||
if (failure instanceof BadRequestException) return;
|
||||
int failures = consecutiveRawWriteFailures.incrementAndGet();
|
||||
rawWriteRetryAfterMs = System.currentTimeMillis() + rawWriteFailureBackoffMs;
|
||||
logger.error("[INFLUX_WRITE_CIRCUIT_OPEN] InfluxDB 原文写入失败,进入快速失败退避: "
|
||||
+ "failures={}, backoffMs={}", failures, rawWriteFailureBackoffMs);
|
||||
}
|
||||
|
||||
private int durationMillisAsInt(java.time.Duration duration) {
|
||||
long millis = duration == null ? 5000L : Math.max(1L, duration.toMillis());
|
||||
return (int) Math.min(Integer.MAX_VALUE, millis);
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入原始 Line Protocol(异步)
|
||||
*/
|
||||
|
||||
+28
-3
@@ -1,15 +1,27 @@
|
||||
package com.influx.raw;
|
||||
|
||||
import com.common.util.Utf8TextTruncator;
|
||||
import com.influxdb.client.domain.WritePrecision;
|
||||
import com.influxdb.client.write.Point;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** 原始 Point 的唯一构造器;V2 的 uuid 只作为 field。 */
|
||||
@Component
|
||||
public class InfluxRawPointFactory {
|
||||
private final RawStorageProperties properties;
|
||||
private final RawInfluxMetrics metrics;
|
||||
|
||||
public InfluxRawPointFactory(RawStorageProperties properties) { this.properties = properties; }
|
||||
@Autowired
|
||||
public InfluxRawPointFactory(RawStorageProperties properties, RawInfluxMetrics metrics) {
|
||||
this.properties = properties;
|
||||
this.metrics = metrics;
|
||||
}
|
||||
|
||||
/** 保留已有单元测试及非 Spring 工具入口。 */
|
||||
public InfluxRawPointFactory(RawStorageProperties properties) {
|
||||
this(properties, new RawInfluxMetrics());
|
||||
}
|
||||
|
||||
public RawPoint create(String eventId, String message, String receiveTime,
|
||||
String deviceId, String deviceCollectId, String originalTopic,
|
||||
@@ -17,21 +29,34 @@ public class InfluxRawPointFactory {
|
||||
require(eventId, "event_id"); require(receiveTime, "receive_time");
|
||||
require(deviceId, "device_id"); require(deviceCollectId, "device_collect_id");
|
||||
require(originalTopic, "originalTopic");
|
||||
Utf8TextTruncator.Result storedMessage = Utf8TextTruncator.truncate(
|
||||
message, properties.getMessageMaxUtf8Bytes());
|
||||
if (storedMessage.isTruncated()) {
|
||||
metrics.messageTruncated(storedMessage.getOriginalUtf8Bytes(), storedMessage.getStoredUtf8Bytes());
|
||||
}
|
||||
String measurement = "syslog_security_" + parsed.getMeasurementDate();
|
||||
if (properties.getWriteSchema() == RawStorageProperties.WriteSchema.V1) {
|
||||
Point point = Point.measurement(measurement)
|
||||
.addTag("device_id", deviceId).addTag("device_collect_id", deviceCollectId)
|
||||
.addTag("uuid", eventId).addTag("topic", originalTopic)
|
||||
.addField("message", message).addField("receive_time", receiveTime)
|
||||
.addField("message", storedMessage.getValue()).addField("receive_time", receiveTime)
|
||||
.addField("message_truncated", storedMessage.isTruncated())
|
||||
.addField("message_original_bytes", storedMessage.getOriginalUtf8Bytes())
|
||||
.addField("message_stored_bytes", storedMessage.getStoredUtf8Bytes())
|
||||
.addField("uuid", eventId).time(parsed.getEpochMillis(), WritePrecision.MS);
|
||||
if (storedMessage.isTruncated()) point.addField("message_original_sha256", storedMessage.getOriginalSha256());
|
||||
return new RawPoint(point, properties.getV1Bucket(), false);
|
||||
}
|
||||
if (pointTimeNs == null) throw new IllegalArgumentException("V2 Point 缺少 point_time_ns");
|
||||
Point point = Point.measurement(measurement)
|
||||
.addTag("device_id", deviceId).addTag("device_collect_id", deviceCollectId)
|
||||
.addTag("topic", originalTopic).addTag("event_bucket", InfluxEventBucket.bucketOf(eventId))
|
||||
.addField("uuid", eventId).addField("message", message).addField("receive_time", receiveTime)
|
||||
.addField("uuid", eventId).addField("message", storedMessage.getValue()).addField("receive_time", receiveTime)
|
||||
.addField("message_truncated", storedMessage.isTruncated())
|
||||
.addField("message_original_bytes", storedMessage.getOriginalUtf8Bytes())
|
||||
.addField("message_stored_bytes", storedMessage.getStoredUtf8Bytes())
|
||||
.time(pointTimeNs, WritePrecision.NS);
|
||||
if (storedMessage.isTruncated()) point.addField("message_original_sha256", storedMessage.getOriginalSha256());
|
||||
return new RawPoint(point, properties.getV2Bucket(), true);
|
||||
}
|
||||
|
||||
|
||||
+25
@@ -16,6 +16,13 @@ public class RawInfluxMetrics {
|
||||
private final LongAdder v2FailedBatches = new LongAdder();
|
||||
private final LongAdder dualReadDuplicate = new LongAdder();
|
||||
private final LongAdder dualReadConflict = new LongAdder();
|
||||
private final LongAdder messagesTruncated = new LongAdder();
|
||||
private final LongAdder originalBytesTruncated = new LongAdder();
|
||||
private final LongAdder storedBytesAfterTruncation = new LongAdder();
|
||||
private final LongAdder rawWriteBypassedBatches = new LongAdder();
|
||||
private final LongAdder rawWriteBypassedMessages = new LongAdder();
|
||||
private final LongAdder continuityDltPublished = new LongAdder();
|
||||
private final LongAdder continuityDltPublishFailed = new LongAdder();
|
||||
|
||||
public void legacyMissing() { legacyMissing.increment(); }
|
||||
public void legacyAssigned() { legacyAssigned.increment(); }
|
||||
@@ -24,6 +31,17 @@ public class RawInfluxMetrics {
|
||||
public void v2FailedBatch() { v2FailedBatches.increment(); }
|
||||
public void dualReadDuplicate() { dualReadDuplicate.increment(); }
|
||||
public void dualReadConflict() { dualReadConflict.increment(); }
|
||||
public void messageTruncated(long originalBytes, long storedBytes) {
|
||||
messagesTruncated.increment();
|
||||
originalBytesTruncated.add(originalBytes);
|
||||
storedBytesAfterTruncation.add(storedBytes);
|
||||
}
|
||||
public void rawWriteBypassed(long messages) {
|
||||
rawWriteBypassedBatches.increment();
|
||||
rawWriteBypassedMessages.add(messages);
|
||||
}
|
||||
public void continuityDltPublished(long messages) { continuityDltPublished.add(messages); }
|
||||
public void continuityDltPublishFailed(long messages) { continuityDltPublishFailed.add(messages); }
|
||||
|
||||
public Map<String, Object> snapshot() {
|
||||
Map<String, Object> values = new LinkedHashMap<>();
|
||||
@@ -36,6 +54,13 @@ public class RawInfluxMetrics {
|
||||
values.put("raw_write_v2_failed_batches_total", v2FailedBatches.sum());
|
||||
values.put("influx_dual_read_duplicate_total", dualReadDuplicate.sum());
|
||||
values.put("influx_dual_read_conflict_total", dualReadConflict.sum());
|
||||
values.put("raw_message_truncated_total", messagesTruncated.sum());
|
||||
values.put("raw_message_truncated_original_bytes_total", originalBytesTruncated.sum());
|
||||
values.put("raw_message_truncated_stored_bytes_total", storedBytesAfterTruncation.sum());
|
||||
values.put("raw_write_bypassed_batches_total", rawWriteBypassedBatches.sum());
|
||||
values.put("raw_write_bypassed_messages_total", rawWriteBypassedMessages.sum());
|
||||
values.put("continuity_dlt_published_total", continuityDltPublished.sum());
|
||||
values.put("continuity_dlt_publish_failed_total", continuityDltPublishFailed.sum());
|
||||
return values;
|
||||
}
|
||||
}
|
||||
|
||||
+12
@@ -19,6 +19,10 @@ public class RawStorageProperties {
|
||||
@Value("${influxdb.raw.legacy-point-time-fallback-enabled:true}") private boolean legacyFallbackEnabled;
|
||||
@Value("${influxdb.raw.query-max-rows:10000}") private int queryMaxRows;
|
||||
@Value("${influxdb.raw.query-max-response-bytes:10485760}") private long queryMaxResponseBytes;
|
||||
/** 原始 message 单字段的 UTF-8 存储上限;0 表示不限制。 */
|
||||
@Value("${influxdb.raw.message-max-utf8-bytes:262144}") private long messageMaxUtf8Bytes;
|
||||
/** 一次同步写请求的估算 Line Protocol 上限;按字节切批,不能只按条数。 */
|
||||
@Value("${influxdb.raw.write-batch-max-bytes:8388608}") private long writeBatchMaxBytes;
|
||||
|
||||
private WriteSchema writeSchema;
|
||||
private ReadMode readMode;
|
||||
@@ -35,6 +39,12 @@ public class RawStorageProperties {
|
||||
if (queryMaxResponseBytes <= 0L) {
|
||||
throw new IllegalArgumentException("influxdb.raw.query-max-response-bytes 必须大于 0");
|
||||
}
|
||||
if (messageMaxUtf8Bytes < 0L || (messageMaxUtf8Bytes > 0L && messageMaxUtf8Bytes < 64L)) {
|
||||
throw new IllegalArgumentException("influxdb.raw.message-max-utf8-bytes 必须为 0 或至少 64");
|
||||
}
|
||||
if (writeBatchMaxBytes <= 0L) {
|
||||
throw new IllegalArgumentException("influxdb.raw.write-batch-max-bytes 必须大于 0");
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
@@ -49,6 +59,8 @@ public class RawStorageProperties {
|
||||
public boolean isLegacyFallbackEnabled() { return legacyFallbackEnabled; }
|
||||
public int getQueryMaxRows() { return queryMaxRows; }
|
||||
public long getQueryMaxResponseBytes() { return queryMaxResponseBytes; }
|
||||
public long getMessageMaxUtf8Bytes() { return messageMaxUtf8Bytes; }
|
||||
public long getWriteBatchMaxBytes() { return writeBatchMaxBytes; }
|
||||
|
||||
public enum WriteSchema { V1, V2 }
|
||||
public enum ReadMode { V1_ONLY, V1_V2, V2_ONLY }
|
||||
|
||||
@@ -60,6 +60,7 @@ spring.kafka.consumer.auto-commit-interval=1000
|
||||
spring.kafka.consumer.topic=test-topic
|
||||
|
||||
|
||||
# 调试修改:dev 环境如需单次最多拉取2000条,将 500 改为 2000。
|
||||
spring.kafka.consumer.max-poll-records=500
|
||||
spring.kafka.consumer.properties.max.poll.interval.ms=900000
|
||||
spring.kafka.consumer.properties.session.timeout.ms=45000
|
||||
|
||||
+1
@@ -64,6 +64,7 @@ spring.kafka.consumer.auto-commit-interval=1000
|
||||
spring.kafka.consumer.topic=agent-syslog-topic
|
||||
|
||||
|
||||
# 调试修改:pre-nw 环境如需单次最多拉取2000条,将 500 改为 2000。
|
||||
spring.kafka.consumer.max-poll-records=500
|
||||
spring.kafka.consumer.properties.max.poll.interval.ms=900000
|
||||
spring.kafka.consumer.properties.session.timeout.ms=45000
|
||||
|
||||
+1
@@ -64,6 +64,7 @@ spring.kafka.consumer.auto-commit-interval=1000
|
||||
spring.kafka.consumer.topic=agent-syslog-topic
|
||||
|
||||
|
||||
# 调试修改:prod-zc 环境如需单次最多拉取2000条,将 500 改为 2000。
|
||||
spring.kafka.consumer.max-poll-records=500
|
||||
spring.kafka.consumer.properties.max.poll.interval.ms=900000
|
||||
spring.kafka.consumer.properties.session.timeout.ms=45000
|
||||
|
||||
+1
@@ -63,6 +63,7 @@ spring.kafka.consumer.topic=agent-01-syslog-topic
|
||||
syslog.raw-consumer.enabled=true
|
||||
|
||||
|
||||
# 通用/Retry消费者上限。RAW底层上限由adaptive-max-records决定(5000),业务基础批量由max-poll-records决定(3000)。
|
||||
spring.kafka.consumer.max-poll-records=500
|
||||
spring.kafka.consumer.properties.max.poll.interval.ms=900000
|
||||
spring.kafka.consumer.properties.session.timeout.ms=45000
|
||||
|
||||
+127
-5
@@ -34,10 +34,30 @@ influxdb.raw.uuid-bucket-count=${INFLUXDB_RAW_UUID_BUCKET_COUNT:4096}
|
||||
influxdb.raw.legacy-point-time-fallback-enabled=${INFLUXDB_RAW_LEGACY_POINT_TIME_FALLBACK_ENABLED:true}
|
||||
influxdb.raw.query-max-rows=${INFLUXDB_RAW_QUERY_MAX_ROWS:10000}
|
||||
influxdb.raw.query-max-response-bytes=${INFLUXDB_RAW_QUERY_MAX_RESPONSE_BYTES:10485760}
|
||||
# 0 表示不限制;启用后最终 message(含截断标记)不超过该 UTF-8 字节数。
|
||||
influxdb.raw.message-max-utf8-bytes=${INFLUXDB_RAW_MESSAGE_MAX_UTF8_BYTES:262144}
|
||||
# Influx 同步写按 Line Protocol 估算字节切批,避免少量大日志形成超大 HTTP 请求。
|
||||
influxdb.raw.write-batch-max-bytes=${INFLUXDB_RAW_WRITE_BATCH_MAX_BYTES:8388608}
|
||||
|
||||
# 现场短时原始日志采样:单会话硬限制仍为最长600秒、最多50条。
|
||||
syslog.raw-capture.enabled=${SYSLOG_RAW_CAPTURE_ENABLED:true}
|
||||
syslog.raw-capture.cluster-enabled=${SYSLOG_RAW_CAPTURE_CLUSTER_ENABLED:true}
|
||||
syslog.raw-capture.max-active-sessions=${SYSLOG_RAW_CAPTURE_MAX_ACTIVE_SESSIONS:20}
|
||||
# 包含已完成且仍可查询的会话,满载时淘汰最早完成的结果。
|
||||
syslog.raw-capture.max-retained-sessions=${SYSLOG_RAW_CAPTURE_MAX_RETAINED_SESSIONS:100}
|
||||
# 给所有消费实例预留会话同步时间;API返回SCHEDULED后从startedAt正式开始计时。
|
||||
syslog.raw-capture.cluster-activation-delay-ms=${SYSLOG_RAW_CAPTURE_CLUSTER_ACTIVATION_DELAY_MS:1000}
|
||||
syslog.raw-capture.cluster-sync-interval-ms=${SYSLOG_RAW_CAPTURE_CLUSTER_SYNC_INTERVAL_MS:200}
|
||||
# 采集停止后继续接收窗口内消息的迟到处理结果,便于异常样本替换普通样本。
|
||||
syslog.raw-capture.settle-seconds=${SYSLOG_RAW_CAPTURE_SETTLE_SECONDS:30}
|
||||
syslog.raw-capture.result-retention-minutes=${SYSLOG_RAW_CAPTURE_RESULT_RETENTION_MINUTES:30}
|
||||
# InfluxDB 2.7 连接超时配置
|
||||
influxdb.connection.timeout=30s
|
||||
influxdb.connection.read-timeout=30s
|
||||
influxdb.connection.write-timeout=60s
|
||||
# 原文写是旁路:单阶段最多等待 5 秒,失败后 30 秒内快速跳过,不能阻塞 Kafka 主消费。
|
||||
influxdb.raw.write-request-timeout=${INFLUXDB_RAW_WRITE_REQUEST_TIMEOUT:5s}
|
||||
influxdb.raw.failure-backoff-ms=${INFLUXDB_RAW_FAILURE_BACKOFF_MS:30000}
|
||||
# Application Configuration
|
||||
app.worker.threads=8
|
||||
app.max.queue.size=10000
|
||||
@@ -70,16 +90,65 @@ spring.kafka.consumer.auto-offset-reset=latest
|
||||
spring.kafka.consumer.enable-auto-commit=false
|
||||
spring.kafka.consumer.auto-commit-interval=1000
|
||||
spring.kafka.consumer.topic=test-topic
|
||||
spring.kafka.consumer.large-topic=${KAFKA_CONSUMER_LARGE_TOPIC:${spring.kafka.consumer.topic}.large}
|
||||
# consumer-rule 是当前活跃的 Kafka 原始日志标准化节点,默认启动监听。
|
||||
syslog.raw-consumer.enabled=true
|
||||
# Raw Topic 当前有 3 个分区,使用独立工厂显式创建 3 个 consumer;可通过环境变量灰度调整。
|
||||
syslog.raw-listener.concurrency=${SYSLOG_RAW_LISTENER_CONCURRENCY:3}
|
||||
# 慢日志统一阈值,默认1000毫秒(1秒):端到端批次、达梦事务、写入排队及非标异步写入。
|
||||
# 达到阈值时打印诊断;0关闭耗时触发的慢日志,但异常/失败仍记录。已有同名环境变量优先。
|
||||
syslog.slow-batch.threshold-ms=${SYSLOG_SLOW_BATCH_THRESHOLD_MS:1000}
|
||||
# 普通业务基础批量3000(保留旧配置名);不再表示底层poll上限。已有同名环境变量仍覆盖基础值。
|
||||
# 目标业务批量=ceil(基础条数*10000/max(普通保留万分比,非标保留万分比)),并受下面5000上限限制。
|
||||
syslog.raw-listener.max-poll-records=${SYSLOG_RAW_LISTENER_MAX_POLL_RECORDS:3000}
|
||||
# 底层RAW max.poll.records固定为此值;无积压时也可能poll到5000,再按3000分块,全部处理后才ACK。
|
||||
# 基础值必须大于0且不超过上限;Retry/大日志/独立统计不采用此自适应策略。
|
||||
syslog.raw-listener.adaptive-max-records=${SYSLOG_RAW_LISTENER_ADAPTIVE_MAX_RECORDS:5000}
|
||||
# 大批次按 Kafka value 序列化字节拆成16MiB业务块,全部完成后提交本次poll;单条不会切断。
|
||||
syslog.raw-listener.processing-batch-max-bytes=${SYSLOG_RAW_PROCESSING_BATCH_MAX_BYTES:16777216}
|
||||
# 每个业务块只向共享规则线程池提交8个worker,避免2000条对应2000个排队任务。
|
||||
syslog.normalization.workers-per-batch=${SYSLOG_NORMALIZATION_WORKERS_PER_BATCH:8}
|
||||
# 连续性优先:特殊/系统性异常优先写 DLT;即使 DLT 失败也记录告警并推进原 offset,避免阻塞分区。
|
||||
syslog.failure-continuity.enabled=${SYSLOG_FAILURE_CONTINUITY_ENABLED:true}
|
||||
# DLT 故障时最多快速等待 1 秒;首次失败后整批直接记录并放行。
|
||||
syslog.failure-continuity.dlt-publish-timeout-ms=${SYSLOG_FAILURE_CONTINUITY_DLT_PUBLISH_TIMEOUT_MS:1000}
|
||||
# Kafka 积压降级采样默认开启;升级应用前必须先创建 syslog_backlog_retention_hourly。
|
||||
syslog.backlog-sampling.enabled=${SYSLOG_BACKLOG_SAMPLING_ENABLED:true}
|
||||
# 使用 syslog-serve 生成的 receive_time 判断端到端延迟;15 分钟内全量保留。
|
||||
# 调试修改:如需改为3分钟,将默认值 900000 改为 180000;若容器设置了
|
||||
# SYSLOG_BACKLOG_SAMPLING_START_LAG_MS,则环境变量优先,必须同步修改或删除该环境变量。
|
||||
syslog.backlog-sampling.start-lag-ms=${SYSLOG_BACKLOG_SAMPLING_START_LAG_MS:900000}
|
||||
# 从免采样窗口结束后开始分级,延迟达到 1 小时时降到最低保留率。
|
||||
syslog.backlog-sampling.lag-threshold-ms=${SYSLOG_BACKLOG_SAMPLING_LAG_THRESHOLD_MS:3600000}
|
||||
# 万分比:这是达到延迟阈值后的最低保留率;识别出的告警永远全量保留。
|
||||
syslog.backlog-sampling.normal-retain-bps=${SYSLOG_BACKLOG_SAMPLING_NORMAL_RETAIN_BPS:1000}
|
||||
syslog.backlog-sampling.non-normal-retain-bps=${SYSLOG_BACKLOG_SAMPLING_NON_NORMAL_RETAIN_BPS:2000}
|
||||
# 默认十级下降:15 分钟到 1 小时的 45 分钟区间,每 4.5 分钟调整一级。
|
||||
syslog.backlog-sampling.degrade-steps=${SYSLOG_BACKLOG_SAMPLING_DEGRADE_STEPS:10}
|
||||
# 调整保留率时同步修改策略版本,便于小时审计区分不同策略。
|
||||
syslog.backlog-sampling.policy-version=${SYSLOG_BACKLOG_SAMPLING_POLICY_VERSION:v2}
|
||||
syslog.backlog-sampling.audit-timeout-seconds=${SYSLOG_BACKLOG_SAMPLING_AUDIT_TIMEOUT_SECONDS:5}
|
||||
syslog.backlog-sampling.audit-retry-backoff-ms=${SYSLOG_BACKLOG_SAMPLING_AUDIT_RETRY_BACKOFF_MS:60000}
|
||||
# 大日志使用独立 Topic、消费组和 ConsumerFactory;建议生产环境独立 JVM 部署。
|
||||
syslog.large-listener.enabled=${SYSLOG_LARGE_LISTENER_ENABLED:true}
|
||||
syslog.large-listener.group-id=${SYSLOG_LARGE_LISTENER_GROUP_ID:${spring.kafka.consumer.group-id}-large}
|
||||
syslog.large-listener.concurrency=${SYSLOG_LARGE_LISTENER_CONCURRENCY:1}
|
||||
syslog.large-listener.max-poll-records=${SYSLOG_LARGE_LISTENER_MAX_POLL_RECORDS:5}
|
||||
syslog.large-listener.max-partition-fetch-bytes=${SYSLOG_LARGE_LISTENER_MAX_PARTITION_FETCH_BYTES:33554432}
|
||||
syslog.large-listener.fetch-max-bytes=${SYSLOG_LARGE_LISTENER_FETCH_MAX_BYTES:67108864}
|
||||
syslog.large-listener.processing-batch-max-bytes=${SYSLOG_LARGE_PROCESSING_BATCH_MAX_BYTES:8388608}
|
||||
# 大日志规则计算不复用普通日志线程池,过载时由 Kafka offset 背压。
|
||||
syslog.large-processor.thread-pool.core-pool-size=${SYSLOG_LARGE_PROCESSOR_CORE_POOL_SIZE:1}
|
||||
syslog.large-processor.thread-pool.max-pool-size=${SYSLOG_LARGE_PROCESSOR_MAX_POOL_SIZE:2}
|
||||
syslog.large-processor.thread-pool.queue-capacity=${SYSLOG_LARGE_PROCESSOR_QUEUE_CAPACITY:10}
|
||||
# P0:Retry/DLT 发布与原始消费使用同一 Kafka 集群;Topic 名称全部可由环境变量覆盖。
|
||||
spring.kafka.bootstrap-servers=${spring.kafka.consumer.bootstrap-servers}
|
||||
spring.kafka.producer.acks=all
|
||||
spring.kafka.producer.properties.enable.idempotence=true
|
||||
spring.kafka.producer.properties.delivery.timeout.ms=120000
|
||||
spring.kafka.producer.properties.request.timeout.ms=30000
|
||||
# Retry/DLT 信封也可能携带大日志密文,不能保留 Kafka 默认 1MiB。
|
||||
spring.kafka.producer.properties.max.request.size=${KAFKA_RELIABILITY_MAX_REQUEST_SIZE:33554432}
|
||||
syslog.reliability.retry-1m-topic=${spring.kafka.consumer.topic}.RETRY.1M
|
||||
syslog.reliability.retry-10m-topic=${spring.kafka.consumer.topic}.RETRY.10M
|
||||
syslog.reliability.retry-1h-topic=${spring.kafka.consumer.topic}.RETRY.1H
|
||||
@@ -91,8 +160,18 @@ syslog.reliability.consumer-version=${APP_VERSION:1.0.0}
|
||||
syslog.reliability.consumer-group-id=${spring.kafka.consumer.group-id}-retry
|
||||
syslog.reliability.consumer.enabled=true
|
||||
syslog.reliability.listener.concurrency=1
|
||||
# 大日志 Retry/DLT 不回流普通重试通道,避免再次形成队头阻塞。
|
||||
syslog.large-reliability.retry-1m-topic=${spring.kafka.consumer.large-topic}.RETRY.1M
|
||||
syslog.large-reliability.retry-10m-topic=${spring.kafka.consumer.large-topic}.RETRY.10M
|
||||
syslog.large-reliability.retry-1h-topic=${spring.kafka.consumer.large-topic}.RETRY.1H
|
||||
syslog.large-reliability.dlt-topic=${spring.kafka.consumer.large-topic}.DLT
|
||||
syslog.large-reliability.replay-topic=${spring.kafka.consumer.large-topic}.REPLAY
|
||||
syslog.large-reliability.consumer-group-id=${spring.kafka.consumer.group-id}-large-retry
|
||||
syslog.large-reliability.consumer.enabled=true
|
||||
|
||||
|
||||
# 通用消费者(如Retry)的上限;RAW底层上限用adaptive-max-records,业务基础值用syslog.raw-listener.max-poll-records。
|
||||
# 使用 prod profile 时 application-prod.properties 中存在同名配置,必须同步修改,否则 prod 值会覆盖本项。
|
||||
spring.kafka.consumer.max-poll-records=500
|
||||
spring.kafka.consumer.properties.max.poll.interval.ms=900000
|
||||
spring.kafka.consumer.properties.session.timeout.ms=45000
|
||||
@@ -108,6 +187,8 @@ spring.task.scheduling.pool.size=10
|
||||
|
||||
# 标准化告警事实与迟到重放通知使用同一个达梦事务。
|
||||
analysis.late-replay.outbox-enabled=${ANALYSIS_LATE_REPLAY_OUTBOX_ENABLED:true}
|
||||
# 告警提交后后台写分钟桶的事务超时;不在主消费线程等待。JDBC/连接池自身超时仍独立生效。
|
||||
analysis.late-replay.notify-timeout-seconds=${ANALYSIS_LATE_REPLAY_NOTIFY_TIMEOUT_SECONDS:5}
|
||||
|
||||
# 日志配置
|
||||
logging.level.com.common.schedule=INFO
|
||||
@@ -149,16 +230,28 @@ app.processor.process-timeout-ms=120000
|
||||
# 失败时只对数据类错误有限二分;
|
||||
# 连接、超时或提交结果未知会立即停止并保留 Kafka offset,禁止放大为逐条请求风暴。
|
||||
dm.standardized-write.mode=BATCH
|
||||
dm.standardized-write.batch-size=${DM_STANDARDIZED_WRITE_BATCH_SIZE:500}
|
||||
# 普通表/告警表每个分组的小批次上限2000行;不足2000直接写入,不等待凑满。
|
||||
dm.standardized-write.batch-size=${DM_STANDARDIZED_WRITE_BATCH_SIZE:2000}
|
||||
dm.standardized-write.writer-concurrency=2
|
||||
dm.standardized-write.writer-queue-capacity=100
|
||||
# 标准化大字段和非标原文均在达梦持久化边界截断;0 表示不限制。
|
||||
# 普通Kafka来源字段上限:默认2KB=2048个UTF-8字节(含截断标记),0关闭本层限制,启用时至少64。
|
||||
# 在规则计算/采样之后限制普通表的文本字段(幂等ID/路由/分区等技术字段除外),告警不应用本层2KB限制,
|
||||
# 以及非标表syslog_message/header_message/reason_detail;不影响InfluxDB原文,大日志不应用2KB限制。
|
||||
# 重试/重放按originalTopic识别;改为4KB填4096。已有同名环境变量会覆盖JAR内默认值。
|
||||
syslog.raw-listener.field-max-utf8-bytes=${SYSLOG_RAW_LISTENER_FIELD_MAX_UTF8_BYTES:2048}
|
||||
# 以下旧限制继续生效(告警也保留原有大字段限制);同时命中时遵循较小上限,关闭上面的限制不会关闭以下限制。
|
||||
dm.normal.large-field-max-utf8-bytes=${DM_NORMAL_LARGE_FIELD_MAX_UTF8_BYTES:262144}
|
||||
dm.normal.large-fields=${DM_NORMAL_LARGE_FIELDS:http_req_body,http_resp_body,http_req_header,http_resp_header,detail,description,cmdline,shell_cmdline,parent_cmdline,mail_message}
|
||||
dm.non-normal.large-field-max-utf8-bytes=${DM_NON_NORMAL_LARGE_FIELD_MAX_UTF8_BYTES:262144}
|
||||
dm.standardized-write.transaction-timeout-seconds=45
|
||||
dm.standardized-write.kafka-batch-deadline-ms=90000
|
||||
dm.standardized-write.max-split-depth=10
|
||||
dm.standardized-write.max-fallback-operations=100
|
||||
dm.standardized-write.circuit-breaker-failure-threshold=3
|
||||
dm.standardized-write.circuit-breaker-backoff-ms=30000
|
||||
dm.non-normal-write.batch-size=${DM_NON_NORMAL_WRITE_BATCH_SIZE:500}
|
||||
# 非标表每条多行INSERT上限2000行;同名环境变量会覆盖JAR默认值。
|
||||
dm.non-normal-write.batch-size=${DM_NON_NORMAL_WRITE_BATCH_SIZE:2000}
|
||||
dm.non-normal-write.queue-capacity=${DM_NON_NORMAL_WRITE_QUEUE_CAPACITY:500}
|
||||
dm.non-normal-write.max-concurrency-retries=${DM_NON_NORMAL_WRITE_MAX_CONCURRENCY_RETRIES:3}
|
||||
dm.non-normal-write.concurrency-retry-backoff-ms=${DM_NON_NORMAL_WRITE_CONCURRENCY_RETRY_BACKOFF_MS:50}
|
||||
@@ -181,11 +274,18 @@ spring.datasource.hikari.validation-timeout=5000
|
||||
spring.datasource.hikari.leak-detection-threshold=30000
|
||||
spring.datasource.hikari.pool-name=HikariPool-SyslogConsumer-rule
|
||||
spring.datasource.hikari.auto-commit=false
|
||||
# 统计写入采用事实同事务直写,不再为每条结果写 change_log + pending。
|
||||
# DIRECT 连续消费优先:事实事务不再写统计Outbox/日统计表,提交后通过有界内存队列异步发布统计。
|
||||
# 首次部署 DIRECT 前必须先执行 08/09/10/11 脚本并按设计文档排空旧 pending。
|
||||
stats.write-mode=DIRECT
|
||||
stats.incremental.capture-enabled=false
|
||||
stats.ingress-metadata.enabled=true
|
||||
# 入口统计独立消费原始Topic,直接聚合写统计表;主消费不再写入口Outbox。
|
||||
# 各节点必须使用同一组名,且不得与业务主消费组相同。
|
||||
stats.ingress-metadata.group-id=${STATS_INGRESS_GROUP_ID:${spring.kafka.consumer.group-id}-ingress-v1}
|
||||
stats.ingress-metadata.large-group-id=${STATS_INGRESS_LARGE_GROUP_ID:${stats.ingress-metadata.group-id}-large}
|
||||
stats.ingress-metadata.max-poll-records=${STATS_INGRESS_MAX_POLL_RECORDS:2000}
|
||||
# 新组默认从Kafka仍保留的最早消息开始,确保不跳过历史接收时间;已有offset继续原位置。
|
||||
stats.ingress-metadata.auto-offset-reset=${STATS_INGRESS_AUTO_OFFSET_RESET:earliest}
|
||||
stats.incremental.read-enabled=true
|
||||
stats.incremental.transaction-timeout-seconds=45
|
||||
stats.device-receive.change-capture-enabled=false
|
||||
@@ -197,11 +297,11 @@ stats.direct.control-table=stats_direct_control
|
||||
stats.direct.today-stats-date-enabled=true
|
||||
stats.direct.max-concurrency-retries=${STATS_DIRECT_MAX_CONCURRENCY_RETRIES:3}
|
||||
stats.direct.concurrency-retry-backoff-ms=${STATS_DIRECT_CONCURRENCY_RETRY_BACKOFF_MS:50}
|
||||
stats.direct.transaction-log-enabled=false
|
||||
stats.direct.transaction-log-enabled=${STATS_DIRECT_TRANSACTION_LOG_ENABLED:false}
|
||||
stats.direct.day-rollover-check-cron=5 * * * * ?
|
||||
stats.business-zone=Asia/Shanghai
|
||||
stats.fact-only.confirm-rebuild-required=false
|
||||
# 事实事务只维护小型精确统计表;提交后按维度脏键异步刷新业务展示字段。
|
||||
# 日统计投影完成后按维度脏键异步刷新业务展示字段。
|
||||
# 三个实例必须配置相同 topic/group-id,Topic 分区数建议与原始 Topic 相同。
|
||||
stats.materialization.enabled=${STATS_MATERIALIZATION_ENABLED:true}
|
||||
stats.materialization.topic=${STATS_MATERIALIZATION_TOPIC:${spring.kafka.consumer.topic}.STATS.MATERIALIZE}
|
||||
@@ -216,6 +316,28 @@ stats.materialization.concurrency-retry-backoff-ms=${STATS_MATERIALIZATION_CONCU
|
||||
stats.materialization.reconcile-initial-delay-ms=${STATS_MATERIALIZATION_RECONCILE_INITIAL_DELAY_MS:30000}
|
||||
stats.materialization.reconcile-interval-ms=${STATS_MATERIALIZATION_RECONCILE_INTERVAL_MS:60000}
|
||||
|
||||
# 事实提交后只做内存offer,独立线程发送到统计Kafka;满队列/进程退出可能少统计,不阻碍事实消费。
|
||||
# enabled=false 会跳过统计并记录损失,绝不回退为同步统计写库。正常保持true。
|
||||
# 旧Outbox继续后台排空,applied表仍用于统计事件去重,不要删表。
|
||||
stats.projection-async.enabled=${STATS_PROJECTION_ASYNC_ENABLED:true}
|
||||
# 队列最多1000个批次聚合事件;含正在重试事件的聚合分组总数最多50000,限制内存占用。
|
||||
stats.projection-async.memory-queue-capacity=${STATS_PROJECTION_MEMORY_QUEUE_CAPACITY:1000}
|
||||
stats.projection-async.memory-max-pending-groups=${STATS_PROJECTION_MEMORY_MAX_PENDING_GROUPS:50000}
|
||||
stats.projection-async.outbox-table=${STATS_PROJECTION_OUTBOX_TABLE:stats_projection_outbox}
|
||||
stats.projection-async.applied-table=${STATS_PROJECTION_APPLIED_TABLE:stats_projection_applied_event}
|
||||
stats.projection-async.topic=${STATS_PROJECTION_TOPIC:${spring.kafka.consumer.topic}.STATS.PROJECTION}
|
||||
stats.projection-async.group-id=${STATS_PROJECTION_GROUP_ID:${spring.kafka.consumer.group-id}-stats-projection}
|
||||
stats.projection-async.relay-interval-ms=${STATS_PROJECTION_RELAY_INTERVAL_MS:200}
|
||||
stats.projection-async.relay-batch-size=${STATS_PROJECTION_RELAY_BATCH_SIZE:100}
|
||||
stats.projection-async.publish-timeout-ms=${STATS_PROJECTION_PUBLISH_TIMEOUT_MS:10000}
|
||||
stats.projection-async.retry-backoff-ms=${STATS_PROJECTION_RETRY_BACKOFF_MS:1000}
|
||||
stats.projection-async.redelivery-interval-ms=${STATS_PROJECTION_REDELIVERY_INTERVAL_MS:60000}
|
||||
stats.projection-async.max-concurrency-retries=${STATS_PROJECTION_MAX_CONCURRENCY_RETRIES:3}
|
||||
stats.projection-async.concurrency-retry-backoff-ms=${STATS_PROJECTION_CONCURRENCY_RETRY_BACKOFF_MS:50}
|
||||
stats.projection-async.retention-days=${STATS_PROJECTION_RETENTION_DAYS:14}
|
||||
stats.projection-async.cleanup-initial-delay-ms=${STATS_PROJECTION_CLEANUP_INITIAL_DELAY_MS:3600000}
|
||||
stats.projection-async.cleanup-interval-ms=${STATS_PROJECTION_CLEANUP_INTERVAL_MS:3600000}
|
||||
|
||||
# 标准化规则编译与批次缓存灰度开关
|
||||
normalization.jetcache.enabled=true
|
||||
normalization.rule-source-cache.enabled=true
|
||||
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.common.mapper.BacklogRetentionAuditMapper">
|
||||
<update id="upsert" parameterType="com.common.service.BacklogRetentionDelta">
|
||||
MERGE INTO syslog_backlog_retention_hourly t
|
||||
USING (
|
||||
SELECT
|
||||
#{sourceHour} AS source_hour,
|
||||
#{sourceTopic} AS source_topic,
|
||||
#{kafkaPartition} AS kafka_partition,
|
||||
#{policyVersion} AS policy_version,
|
||||
#{normalRetainBps} AS normal_retain_bps,
|
||||
#{nonNormalRetainBps} AS non_normal_retain_bps,
|
||||
#{messageTotal} AS message_total,
|
||||
#{alarmRowsTotal} AS alarm_rows_total,
|
||||
#{alarmRowsSaved} AS alarm_rows_saved,
|
||||
#{normalRowsTotal} AS normal_rows_total,
|
||||
#{normalRowsSaved} AS normal_rows_saved,
|
||||
#{normalRowsDropped} AS normal_rows_dropped,
|
||||
#{nonNormalRowsTotal} AS non_normal_rows_total,
|
||||
#{nonNormalRowsSaved} AS non_normal_rows_saved,
|
||||
#{nonNormalRowsDropped} AS non_normal_rows_dropped,
|
||||
#{rawTotal} AS raw_total,
|
||||
#{rawSaved} AS raw_saved,
|
||||
#{rawDropped} AS raw_dropped,
|
||||
#{minLagMs} AS min_lag_ms,
|
||||
#{maxLagMs} AS max_lag_ms
|
||||
FROM dual
|
||||
) s
|
||||
ON (
|
||||
t.source_hour = s.source_hour
|
||||
AND t.source_topic = s.source_topic
|
||||
AND t.kafka_partition = s.kafka_partition
|
||||
AND t.policy_version = s.policy_version
|
||||
AND t.normal_retain_bps = s.normal_retain_bps
|
||||
AND t.non_normal_retain_bps = s.non_normal_retain_bps
|
||||
)
|
||||
WHEN MATCHED THEN UPDATE SET
|
||||
t.message_total = t.message_total + s.message_total,
|
||||
t.alarm_rows_total = t.alarm_rows_total + s.alarm_rows_total,
|
||||
t.alarm_rows_saved = t.alarm_rows_saved + s.alarm_rows_saved,
|
||||
t.normal_rows_total = t.normal_rows_total + s.normal_rows_total,
|
||||
t.normal_rows_saved = t.normal_rows_saved + s.normal_rows_saved,
|
||||
t.normal_rows_dropped = t.normal_rows_dropped + s.normal_rows_dropped,
|
||||
t.non_normal_rows_total = t.non_normal_rows_total + s.non_normal_rows_total,
|
||||
t.non_normal_rows_saved = t.non_normal_rows_saved + s.non_normal_rows_saved,
|
||||
t.non_normal_rows_dropped = t.non_normal_rows_dropped + s.non_normal_rows_dropped,
|
||||
t.raw_total = t.raw_total + s.raw_total,
|
||||
t.raw_saved = t.raw_saved + s.raw_saved,
|
||||
t.raw_dropped = t.raw_dropped + s.raw_dropped,
|
||||
t.min_lag_ms = CASE WHEN t.min_lag_ms < s.min_lag_ms THEN t.min_lag_ms ELSE s.min_lag_ms END,
|
||||
t.max_lag_ms = CASE WHEN t.max_lag_ms > s.max_lag_ms THEN t.max_lag_ms ELSE s.max_lag_ms END,
|
||||
t.updated_at = SYSDATE
|
||||
WHEN NOT MATCHED THEN INSERT (
|
||||
source_hour, source_topic, kafka_partition, policy_version,
|
||||
normal_retain_bps, non_normal_retain_bps, message_total,
|
||||
alarm_rows_total, alarm_rows_saved, normal_rows_total, normal_rows_saved,
|
||||
normal_rows_dropped, non_normal_rows_total, non_normal_rows_saved,
|
||||
non_normal_rows_dropped, raw_total, raw_saved, raw_dropped,
|
||||
min_lag_ms, max_lag_ms, created_at, updated_at
|
||||
) VALUES (
|
||||
s.source_hour, s.source_topic, s.kafka_partition, s.policy_version,
|
||||
s.normal_retain_bps, s.non_normal_retain_bps, s.message_total,
|
||||
s.alarm_rows_total, s.alarm_rows_saved, s.normal_rows_total, s.normal_rows_saved,
|
||||
s.normal_rows_dropped, s.non_normal_rows_total, s.non_normal_rows_saved,
|
||||
s.non_normal_rows_dropped, s.raw_total, s.raw_saved, s.raw_dropped,
|
||||
s.min_lag_ms, s.max_lag_ms, SYSDATE, SYSDATE
|
||||
)
|
||||
</update>
|
||||
</mapper>
|
||||
+4
@@ -70,6 +70,10 @@
|
||||
FROM device_device
|
||||
</select>
|
||||
|
||||
<select id="selectAllIds" resultType="java.lang.Long">
|
||||
SELECT id FROM device_device
|
||||
</select>
|
||||
|
||||
<!-- 根据IP查询 -->
|
||||
<select id="selectByIp" parameterType="java.lang.String" resultMap="BaseResultMap">
|
||||
SELECT
|
||||
|
||||
+11
@@ -96,6 +96,17 @@
|
||||
WHERE normalize_rule_id = #{ruleId}
|
||||
</select>
|
||||
|
||||
<select id="selectRuleIdsByDeviceId" parameterType="java.lang.Long" resultType="java.lang.Long">
|
||||
SELECT normalize_rule_id
|
||||
FROM dm_normalize_rule_device
|
||||
WHERE device_id = #{deviceId}
|
||||
</select>
|
||||
|
||||
<select id="selectAllAssociatedDeviceIds" resultType="java.lang.Long">
|
||||
SELECT DISTINCT device_id
|
||||
FROM dm_normalize_rule_device
|
||||
</select>
|
||||
|
||||
|
||||
<!-- 根据ID和租户ID查询 -->
|
||||
<select id="selectByIdAndTenant" resultMap="BaseResultMap">
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.Modules.NormalData;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AdaptiveRawBatchSizerTest {
|
||||
@Test void newBaseStartsAt3000AndDegradedRatesAreCappedAt5000() {
|
||||
AdaptiveRawBatchSizer sizer = new AdaptiveRawBatchSizer(3000, 5000);
|
||||
assertEquals(3000, sizer.targetRecords(10000, 10000));
|
||||
assertEquals(3750, sizer.targetRecords(8000, 8000));
|
||||
assertEquals(5000, sizer.targetRecords(6000, 6000));
|
||||
assertEquals(5000, sizer.targetRecords(1000, 2000));
|
||||
}
|
||||
|
||||
@Test void largerCapKeepsDefaultRetentionTargetAndAllowsFiveThousand() {
|
||||
AdaptiveRawBatchSizer sizer = new AdaptiveRawBatchSizer(500, 5000);
|
||||
assertEquals(500, sizer.targetRecords(10000, 10000));
|
||||
assertEquals(2500, sizer.targetRecords(1000, 2000));
|
||||
assertEquals(5000, sizer.targetRecords(1000, 1000));
|
||||
assertEquals(5000, sizer.targetRecords(0, 0));
|
||||
}
|
||||
|
||||
@Test void derivesMultiplierAndCapsWithoutPerStageConfiguration() {
|
||||
AdaptiveRawBatchSizer sizer = new AdaptiveRawBatchSizer(500, 3000);
|
||||
assertEquals(500, sizer.targetRecords(10000, 10000));
|
||||
assertEquals(1000, sizer.targetRecords(5000, 5000));
|
||||
assertEquals(2000, sizer.targetRecords(2500, 2500));
|
||||
assertEquals(2500, sizer.targetRecords(1000, 2000));
|
||||
assertEquals(3000, sizer.targetRecords(1000, 1000));
|
||||
assertEquals(3000, sizer.targetRecords(0, 0));
|
||||
assertEquals(500, sizer.targetRecords(0, 10000));
|
||||
assertEquals(500, sizer.targetRecords(10000, 0));
|
||||
assertEquals(834, sizer.targetRecords(5000, 6000));
|
||||
}
|
||||
|
||||
@Test void supportsOtherBaseSizesWithoutOverflow() {
|
||||
assertEquals(3000, new AdaptiveRawBatchSizer(1000, 3000).targetRecords(1000, 2000));
|
||||
assertEquals(Integer.MAX_VALUE,
|
||||
new AdaptiveRawBatchSizer(Integer.MAX_VALUE, Integer.MAX_VALUE).targetRecords(1, 1));
|
||||
}
|
||||
|
||||
@Test void rejectsInvalidConfigurationAndRates() {
|
||||
assertThrows(IllegalArgumentException.class, () -> new AdaptiveRawBatchSizer(0, 3000));
|
||||
assertThrows(IllegalArgumentException.class, () -> new AdaptiveRawBatchSizer(500, 499));
|
||||
AdaptiveRawBatchSizer sizer = new AdaptiveRawBatchSizer(500, 3000);
|
||||
assertThrows(IllegalArgumentException.class, () -> sizer.targetRecords(-1, 2000));
|
||||
assertThrows(IllegalArgumentException.class, () -> sizer.targetRecords(1000, 10001));
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.Modules.NormalData;
|
||||
|
||||
import com.config.BacklogSamplingProperties;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class BacklogSamplingDeciderTest {
|
||||
private BacklogSamplingProperties properties;
|
||||
private BacklogSamplingDecider decider;
|
||||
private final Instant now = Instant.parse("2026-09-12T12:00:00Z");
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
properties = new BacklogSamplingProperties();
|
||||
ReflectionTestUtils.setField(properties, "enabled", true);
|
||||
ReflectionTestUtils.setField(properties, "startLagMs", 900_000L);
|
||||
ReflectionTestUtils.setField(properties, "lagThresholdMs", 3_600_000L);
|
||||
ReflectionTestUtils.setField(properties, "normalRetainBps", 0);
|
||||
ReflectionTestUtils.setField(properties, "nonNormalRetainBps", 0);
|
||||
ReflectionTestUtils.setField(properties, "degradeSteps", 10);
|
||||
ReflectionTestUtils.setField(properties, "policyVersion", "test-v1");
|
||||
decider = new BacklogSamplingDecider(properties);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recentMessageIsFullyRetained() {
|
||||
BacklogSamplingDecision decision = decider.decide("event", LocalDateTime.of(2026, 9, 12, 19, 58),
|
||||
false, true, false, now);
|
||||
|
||||
assertFalse(decision.isDegraded());
|
||||
assertTrue(decision.isKeepNormal());
|
||||
assertTrue(decision.isKeepRaw());
|
||||
}
|
||||
|
||||
@Test
|
||||
void oldNormalMessageCanDropBothDmRowAndRawPoint() {
|
||||
BacklogSamplingDecision decision = decider.decide("event", LocalDateTime.of(2026, 9, 12, 18, 0),
|
||||
false, true, false, now);
|
||||
|
||||
assertTrue(decision.isDegraded());
|
||||
assertFalse(decision.isKeepNormal());
|
||||
assertFalse(decision.isKeepRaw());
|
||||
}
|
||||
|
||||
@Test
|
||||
void oldAlarmAlwaysKeepsRawEvenAtZeroNormalRate() {
|
||||
BacklogSamplingDecision decision = decider.decide("event", LocalDateTime.of(2026, 9, 12, 18, 0),
|
||||
true, false, false, now);
|
||||
|
||||
assertTrue(decision.isDegraded());
|
||||
assertTrue(decision.isKeepRaw());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stableHashReturnsSameDecisionForReplay() {
|
||||
boolean first = BacklogSamplingDecider.sampled("event-42", "NORMAL", 3210, "v7");
|
||||
boolean second = BacklogSamplingDecider.sampled("event-42", "NORMAL", 3210, "v7");
|
||||
|
||||
assertTrue(first == second);
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledPolicyRetainsOldMessagesInFull() {
|
||||
ReflectionTestUtils.setField(properties, "enabled", false);
|
||||
|
||||
BacklogSamplingDecision decision = decider.decide("event",
|
||||
LocalDateTime.of(2000, 1, 1, 0, 0), false, true, true, now);
|
||||
|
||||
assertFalse(decision.isDegraded());
|
||||
assertTrue(decision.isKeepNormal());
|
||||
assertTrue(decision.isKeepNonNormal());
|
||||
assertTrue(decision.isKeepRaw());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fifteenMinuteGraceAndRemainingWindowAreSplitIntoTenEqualSteps() {
|
||||
ReflectionTestUtils.setField(properties, "normalRetainBps", 1000);
|
||||
ReflectionTestUtils.setField(properties, "nonNormalRetainBps", 2000);
|
||||
|
||||
BacklogSamplingDecision fifteenMinutes = decider.decide("event-15m",
|
||||
LocalDateTime.of(2026, 9, 12, 19, 45), false, true, false, now);
|
||||
BacklogSamplingDecision nineteenMinutes = decider.decide("event-19m",
|
||||
LocalDateTime.of(2026, 9, 12, 19, 41), false, true, false, now);
|
||||
BacklogSamplingDecision twentyMinutes = decider.decide("event-20m",
|
||||
LocalDateTime.of(2026, 9, 12, 19, 40), false, true, false, now);
|
||||
BacklogSamplingDecision thirtyEightMinutes = decider.decide("event-38m",
|
||||
LocalDateTime.of(2026, 9, 12, 19, 22), false, true, false, now);
|
||||
BacklogSamplingDecision oneHour = decider.decide("event-60m",
|
||||
LocalDateTime.of(2026, 9, 12, 19, 0), false, true, false, now);
|
||||
|
||||
assertFalse(fifteenMinutes.isDegraded());
|
||||
assertFalse(nineteenMinutes.isDegraded());
|
||||
assertEquals(9100, twentyMinutes.getNormalRetainBps());
|
||||
assertEquals(5500, thirtyEightMinutes.getNormalRetainBps());
|
||||
assertEquals(1000, oneHour.getNormalRetainBps());
|
||||
assertEquals(2000, oneHour.getNonNormalRetainBps());
|
||||
}
|
||||
|
||||
@Test
|
||||
void currentStepUsesGraceWindowAndReachesMinimumAtThreshold() {
|
||||
assertEquals(0, BacklogSamplingDecider.currentStep(900_000L, 900_000L, 3_600_000L, 10));
|
||||
assertEquals(0, BacklogSamplingDecider.currentStep(1_169_999L, 900_000L, 3_600_000L, 10));
|
||||
assertEquals(1, BacklogSamplingDecider.currentStep(1_170_000L, 900_000L, 3_600_000L, 10));
|
||||
assertEquals(9, BacklogSamplingDecider.currentStep(3_599_999L, 900_000L, 3_600_000L, 10));
|
||||
assertEquals(10, BacklogSamplingDecider.currentStep(3_600_000L, 900_000L, 3_600_000L, 10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void startLagMustBeLowerThanMinimumRateThreshold() {
|
||||
ReflectionTestUtils.setField(properties, "startLagMs", 3_600_000L);
|
||||
|
||||
IllegalArgumentException failure = assertThrows(
|
||||
IllegalArgumentException.class, properties::validate);
|
||||
|
||||
assertTrue(failure.getMessage().contains("start-lag-ms"));
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -61,6 +61,7 @@ class LogNormalProcessorCompiledEquivalenceTest {
|
||||
assertEquals(legacyResult.getRows(), compiledResult.getRows());
|
||||
assertEquals(1, compiledResult.getRows().size());
|
||||
assertEquals(31L, compiledResult.getRows().get(0).get("normalize_rule_id"));
|
||||
assertEquals("CN", compiledResult.getRows().get(0).get("country"));
|
||||
assertEquals(1, metrics.getParseMisses());
|
||||
assertEquals(1, metrics.getParseHits());
|
||||
assertEquals(2, metrics.getCompiledMisses());
|
||||
@@ -98,10 +99,11 @@ class LogNormalProcessorCompiledEquivalenceTest {
|
||||
+ "\"mappers\":["
|
||||
+ "{\"origin_field\":\"src_ip\",\"dest_field\":\"src_ip\",\"action\":{\"type\":\"equal\",\"param\":{}}},"
|
||||
+ "{\"origin_field\":\"level\",\"dest_field\":\"severity\",\"action\":{\"type\":\"mapping\",\"param\":{\"mapping\":{\"high\":3}}}}],"
|
||||
+ "\"filters_params\":{\"expressions\":[]},"
|
||||
+ "\"complete_columns\":[{\"column_name\":\"country\",\"value\":\"CN\","
|
||||
+ "\"filters_relation\":\"and\",\"conditions\":[{\"column_name\":\"src_ip\","
|
||||
+ "\"op\":\"regexp\",\"value\":\"10\\\\..*\"}]}]}";
|
||||
+ "\"filters_params\":\"{\\\"expressions\\\":[]}\","
|
||||
+ "\"complete_columns\":\"[{\\\"column_name\\\":\\\"country\\\","
|
||||
+ "\\\"value\\\":\\\"CN\\\",\\\"filters_relation\\\":\\\"and\\\","
|
||||
+ "\\\"conditions\\\":[{\\\"column_name\\\":\\\"src_ip\\\","
|
||||
+ "\\\"op\\\":\\\"regexp\\\",\\\"value\\\":\\\"10\\\\\\\\..*\\\"}]}]\"}";
|
||||
return new RuleSource(id, name, name, "json", content, true, "0");
|
||||
}
|
||||
|
||||
|
||||
+111
-11
@@ -106,37 +106,117 @@ class LogNormalProcessorRuleSelectionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidJsonStopsAtFirstJsonRuleAndGoesDirectlyToDeferredNonNormal() {
|
||||
void invalidJsonCandidateDoesNotStopLaterMatchingRule() {
|
||||
RuleSource invalidJson = jsonRule(10L, "json-first", "", equalMapping(), "");
|
||||
RuleSource regexWouldMatch = regexRule(20L, "regex-second", "value=(\\S+)");
|
||||
RuleSource regexWouldMatch = regexRuleWithCropper(
|
||||
20L, "regex-second", "value=(\\S+)", "value=");
|
||||
Fixture fixture = fixture(Arrays.asList(invalidJson, regexWouldMatch), config(true));
|
||||
|
||||
LogNormalProcessor.NormalizationResult result = fixture.prepareActive(
|
||||
"value=ok {\"broken\":\"unterminated");
|
||||
|
||||
assertEquals(LogNormalProcessor.ProcessingOutcome.FILTERED, result.getOutcome());
|
||||
assertTrue(result.getRows().isEmpty());
|
||||
assertEquals(1, result.getNonNormalMessages().size());
|
||||
assertEquals("JSON解析异常", result.getNonNormalMessages().get(0).getReason());
|
||||
assertTrue(result.getNonNormalMessages().get(0).getReasonDetail().contains("ruleId=10"));
|
||||
assertEquals(LogNormalProcessor.ProcessingOutcome.SUCCESS, result.getOutcome());
|
||||
assertEquals(1, result.getRows().size());
|
||||
assertEquals(20L, result.getRows().get(0).get("normalize_rule_id"));
|
||||
assertTrue(result.getNonNormalMessages().isEmpty());
|
||||
verify(fixture.nonNormalService, never()).saveMessage(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonWithoutObjectBoundaryAlsoGoesDirectlyToDeferredNonNormal() {
|
||||
void invalidJsonCandidateDoesNotStopLaterMatchingRuleInLegacyParser() {
|
||||
RuleSource invalidJson = jsonRule(10L, "json-first", "", equalMapping(), "");
|
||||
RuleSource regexWouldMatch = regexRuleWithCropper(
|
||||
20L, "regex-second", "value=(\\S+)", "value=");
|
||||
Fixture fixture = fixture(Arrays.asList(invalidJson, regexWouldMatch), config(false));
|
||||
|
||||
LogNormalProcessor.NormalizationResult result = fixture.prepareActive(
|
||||
"value=ok {\"broken\":\"unterminated");
|
||||
|
||||
assertEquals(LogNormalProcessor.ProcessingOutcome.SUCCESS, result.getOutcome());
|
||||
assertEquals(1, result.getRows().size());
|
||||
assertEquals(20L, result.getRows().get(0).get("normalize_rule_id"));
|
||||
assertTrue(result.getNonNormalMessages().isEmpty());
|
||||
verify(fixture.nonNormalService, never()).saveMessage(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonWithoutObjectBoundaryDoesNotStopLaterMatchingRule() {
|
||||
RuleSource invalidJson = new RuleSource(10L, "json-no-cropper", "json-no-cropper",
|
||||
"json", "{\"mappers\":[" + equalMapping()
|
||||
+ "],\"complete_columns\":[]}", true, "0");
|
||||
RuleSource regexWouldMatch = regexRule(20L, "regex-second", "value=(\\S+)");
|
||||
RuleSource regexWouldMatch = regexRuleWithCropper(
|
||||
20L, "regex-second", "value=(\\S+)", "value=");
|
||||
Fixture fixture = fixture(Arrays.asList(invalidJson, regexWouldMatch), config(true));
|
||||
|
||||
LogNormalProcessor.NormalizationResult result = fixture.prepareActive("value=ok");
|
||||
|
||||
assertEquals(LogNormalProcessor.ProcessingOutcome.SUCCESS, result.getOutcome());
|
||||
assertEquals(1, result.getRows().size());
|
||||
assertEquals(20L, result.getRows().get(0).get("normalize_rule_id"));
|
||||
assertTrue(result.getNonNormalMessages().isEmpty());
|
||||
verify(fixture.nonNormalService, never()).saveMessage(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void threatbookUsesTdpRuleAfterFixedOffsetHoneypotRulesAreRejected() {
|
||||
String honeypotMapping = "{\"origin_field\":\"title\",\"dest_field\":\"device_name\","
|
||||
+ "\"action\":{\"type\":\"equal\",\"param\":{}}}";
|
||||
String tdpMapping = "{\"origin_field\":\"machine\",\"dest_field\":\"victim_ip\","
|
||||
+ "\"action\":{\"type\":\"equal\",\"param\":{}}}";
|
||||
RuleSource honeypotV12 = jsonRuleWithCropper(158L, "weibujsomv2",
|
||||
"<", 58, honeypotMapping);
|
||||
RuleSource honeypotV13 = jsonRuleWithCropper(159L, "weibujson",
|
||||
"<", 57, honeypotMapping);
|
||||
RuleSource tdp = jsonRuleWithCropper(150L, "weibu_TDP_alarmlog_JSON",
|
||||
"{", -1, tdpMapping);
|
||||
Fixture fixture = fixture(Arrays.asList(honeypotV12, honeypotV13, tdp), config(true));
|
||||
|
||||
LogNormalProcessor.NormalizationResult result = fixture.prepareActive(
|
||||
"<1>2026-09-14T03:34:12+08:00 localhost.localdomain Threatbook[2477960]: "
|
||||
+ "{\"time\":1789328052,\"machine\":\"10.174.2.19\","
|
||||
+ "\"net\":{\"http\":{\"reqs_body\":"
|
||||
+ "\"{\\\"operatorID\\\":\\\"MA59RW1N3\\\"}\"}}}");
|
||||
|
||||
assertEquals(LogNormalProcessor.ProcessingOutcome.SUCCESS, result.getOutcome());
|
||||
assertEquals(1, result.getRows().size());
|
||||
assertEquals(150L, result.getRows().get(0).get("normalize_rule_id"));
|
||||
assertEquals("10.174.2.19", result.getRows().get(0).get("victim_ip"));
|
||||
assertTrue(result.getNonNormalMessages().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void skyeyeCropperPrefixIsNarrowedToOuterJsonBeforeJackson() {
|
||||
RuleSource skyeye = jsonRuleWithCropper(129L, "skyeye",
|
||||
"|!alarm|!{", -1, equalMapping());
|
||||
RuleSource unrelated = regexRule(200L, "unrelated", "never=(\\S+)");
|
||||
Fixture fixture = fixture(Arrays.asList(skyeye, unrelated), config(true));
|
||||
|
||||
LogNormalProcessor.NormalizationResult result = fixture.prepareActive(
|
||||
"<158>Sep 14 11:07:16 host SyslogClient[1]: "
|
||||
+ "2026-09-14 11:07:16|!10.56.170.107|!alarm|!"
|
||||
+ "{\"status\":\"ok\",\"payload\":{\"rsp_header\":\"a\\r\\nb\"}}");
|
||||
|
||||
assertEquals(LogNormalProcessor.ProcessingOutcome.SUCCESS, result.getOutcome());
|
||||
assertEquals(1, result.getRows().size());
|
||||
assertEquals(129L, result.getRows().get(0).get("normalize_rule_id"));
|
||||
assertEquals("ok", result.getRows().get(0).get("action"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allApplicableJsonCandidatesInvalidStillProduceJsonException() {
|
||||
RuleSource first = jsonRuleWithCropper(10L, "first", "marker={", -1,
|
||||
equalMapping());
|
||||
RuleSource second = jsonRuleWithCropper(20L, "second", "marker={", -1,
|
||||
equalMapping());
|
||||
Fixture fixture = fixture(Arrays.asList(first, second), config(true));
|
||||
|
||||
LogNormalProcessor.NormalizationResult result = fixture.prepareActive(
|
||||
"marker={\"broken\":\"unterminated");
|
||||
|
||||
assertEquals(LogNormalProcessor.ProcessingOutcome.FILTERED, result.getOutcome());
|
||||
assertTrue(result.getRows().isEmpty());
|
||||
assertEquals(1, result.getNonNormalMessages().size());
|
||||
assertEquals("JSON解析异常", result.getNonNormalMessages().get(0).getReason());
|
||||
verify(fixture.nonNormalService, never()).saveMessage(any());
|
||||
assertTrue(result.getNonNormalMessages().get(0).getReasonDetail().contains("ruleId=10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -250,6 +330,26 @@ class LogNormalProcessorRuleSelectionTest {
|
||||
return new RuleSource(id, name, name, "regex", content, true, "0");
|
||||
}
|
||||
|
||||
private static RuleSource regexRuleWithCropper(long id, String name, String regexp,
|
||||
String headKey) {
|
||||
String content = "{\"cropper_params\":{\"head_key\":\"" + headKey
|
||||
+ "\",\"head_offset\":0,\"tail_key\":\"\",\"tail_offset\":0},"
|
||||
+ "\"regexp\":\"" + regexp.replace("\\", "\\\\") + "\","
|
||||
+ "\"mappers\":[{\"origin_field\":\"1\",\"dest_field\":\"value\","
|
||||
+ "\"action\":{\"type\":\"equal\",\"param\":{}}}]}";
|
||||
return new RuleSource(id, name, name, "regex", content, true, "0");
|
||||
}
|
||||
|
||||
private static RuleSource jsonRuleWithCropper(long id, String name, String headKey,
|
||||
int headOffset, String mapper) {
|
||||
String escapedHeadKey = headKey.replace("\\", "\\\\").replace("\"", "\\\"");
|
||||
String content = "{\"cropper_params\":{\"head_key\":\"" + escapedHeadKey
|
||||
+ "\",\"head_offset\":" + headOffset
|
||||
+ ",\"tail_key\":\"\",\"tail_offset\":0},"
|
||||
+ "\"mappers\":[" + mapper + "],\"complete_columns\":[]}";
|
||||
return new RuleSource(id, name, name, "json", content, true, "0");
|
||||
}
|
||||
|
||||
private static String equalMapping() {
|
||||
return "{\"origin_field\":\"status\",\"dest_field\":\"action\","
|
||||
+ "\"action\":{\"type\":\"equal\",\"param\":{}}}";
|
||||
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
package com.Modules.NormalData;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.kafka.support.Acknowledgment;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class SysLogAdaptiveRawBatchTest {
|
||||
private SysLogProcessor processor;
|
||||
private Acknowledgment ack;
|
||||
|
||||
@BeforeEach void setup() {
|
||||
processor = spy(new SysLogProcessor());
|
||||
// 保留对旧基础值覆盖配置的回归场景;新默认值另行验证。
|
||||
ReflectionTestUtils.setField(processor, "adaptiveRawBatchSizer", new AdaptiveRawBatchSizer(500, 5000));
|
||||
ReflectionTestUtils.setField(processor, "taskExecutor", (Executor) Runnable::run);
|
||||
ReflectionTestUtils.setField(processor, "largeTaskExecutor", (Executor) Runnable::run);
|
||||
ReflectionTestUtils.setField(processor, "largeProcessingBatchMaxBytes", 16777216L);
|
||||
ReflectionTestUtils.setField(processor, "failureContinuityEnabled", false);
|
||||
ack = mock(Acknowledgment.class);
|
||||
}
|
||||
|
||||
@Test void newBaseSplitsAt3000ThenBacklogCanUse5000WithoutEarlyAck() {
|
||||
ReflectionTestUtils.setField(processor, "adaptiveRawBatchSizer", new AdaptiveRawBatchSizer(3000, 5000));
|
||||
List<Integer> sizes = new ArrayList<>();
|
||||
doAnswer(call -> {
|
||||
sizes.add(((List<?>) call.getArgument(0)).size());
|
||||
verifyNoInteractions(ack);
|
||||
processor.observeRawRetention(2000);
|
||||
return null;
|
||||
}).when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
processor.consumeAndParallelProcess(records(5000), ack);
|
||||
assertEquals(Arrays.asList(3000, 2000), sizes);
|
||||
verify(ack).acknowledge();
|
||||
clearInvocations(ack);
|
||||
sizes.clear();
|
||||
processor.consumeAndParallelProcess(records(5000), ack);
|
||||
assertEquals(Collections.singletonList(5000), sizes);
|
||||
verify(ack).acknowledge();
|
||||
}
|
||||
|
||||
@Test void livePollSplitsInto500WithoutEarlyAckOrRecordLoss() {
|
||||
List<Integer> sizes = new ArrayList<>();
|
||||
List<Long> offsets = new ArrayList<>();
|
||||
doAnswer(call -> {
|
||||
List<ConsumerRecord<String, String>> chunk = call.getArgument(0);
|
||||
sizes.add(chunk.size());
|
||||
chunk.forEach(record -> offsets.add(record.offset()));
|
||||
verifyNoInteractions(ack);
|
||||
processor.observeRawRetention(10000);
|
||||
return null;
|
||||
}).when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
processor.consumeAndParallelProcess(records(5000), ack);
|
||||
assertEquals(Collections.nCopies(10, 500), sizes);
|
||||
for (int i = 0; i < 5000; i++) assertEquals((long) i, offsets.get(i).longValue());
|
||||
verify(ack).acknowledge();
|
||||
}
|
||||
|
||||
@Test void backlogExpandsNextChunkAndRecoveryShrinksFollowingChunk() {
|
||||
List<Integer> sizes = new ArrayList<>();
|
||||
doAnswer(call -> {
|
||||
sizes.add(((List<?>) call.getArgument(0)).size());
|
||||
processor.observeRawRetention(2000);
|
||||
return null;
|
||||
}).when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
processor.consumeAndParallelProcess(records(3000), ack);
|
||||
assertEquals(Arrays.asList(500, 2500), sizes);
|
||||
sizes.clear();
|
||||
doAnswer(call -> {
|
||||
sizes.add(((List<?>) call.getArgument(0)).size());
|
||||
processor.observeRawRetention(10000);
|
||||
return null;
|
||||
}).when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
processor.consumeAndParallelProcess(records(3000), ack);
|
||||
assertEquals(Arrays.asList(2500, 500), sizes);
|
||||
sizes.clear();
|
||||
processor.consumeAndParallelProcess(records(3000), ack);
|
||||
assertEquals(Arrays.asList(500, 500, 500, 500, 500, 500), sizes);
|
||||
verify(ack, times(3)).acknowledge();
|
||||
}
|
||||
|
||||
@Test void tenPercentHits5000CapAndIncompleteTailIsNotHeldWaitingForMore() {
|
||||
processor.observeRawRetention(1000);
|
||||
List<Integer> sizes = new ArrayList<>();
|
||||
doAnswer(call -> { sizes.add(((List<?>) call.getArgument(0)).size()); return null; })
|
||||
.when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
processor.consumeAndParallelProcess(records(5000), ack);
|
||||
processor.consumeAndParallelProcess(records(17), ack);
|
||||
assertEquals(Arrays.asList(5000, 17), sizes);
|
||||
}
|
||||
|
||||
@Test void bytesLimitStillWinsAndOversizedSingleRecordIsNotLost() {
|
||||
List<ConsumerRecord<String, String>> records = Arrays.asList(
|
||||
new ConsumerRecord<>("raw", 0, 0, "k", "中"),
|
||||
new ConsumerRecord<>("raw", 0, 1, "k", "中"),
|
||||
new ConsumerRecord<>("raw", 0, 2, "k", "oversized"),
|
||||
new ConsumerRecord<>("raw", 0, 3, "k", "x"));
|
||||
ReflectionTestUtils.setField(processor, "rawProcessingBatchMaxBytes", 3L);
|
||||
processor.observeRawRetention(1000);
|
||||
List<Integer> sizes = new ArrayList<>();
|
||||
List<Long> offsets = new ArrayList<>();
|
||||
doAnswer(call -> {
|
||||
List<ConsumerRecord<String, String>> chunk = call.getArgument(0);
|
||||
sizes.add(chunk.size());
|
||||
chunk.forEach(record -> offsets.add(record.offset()));
|
||||
return null;
|
||||
}).when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
processor.consumeAndParallelProcess(records, ack);
|
||||
assertEquals(Arrays.asList(1, 1, 1, 1), sizes);
|
||||
assertEquals(Arrays.asList(0L, 1L, 2L, 3L), offsets);
|
||||
verify(ack).acknowledge();
|
||||
}
|
||||
|
||||
@Test void failingLaterChunkDoesNotCommitUnfinishedPollAndResetsToBase() {
|
||||
List<Integer> sizes = new ArrayList<>();
|
||||
doAnswer(call -> {
|
||||
sizes.add(((List<?>) call.getArgument(0)).size());
|
||||
processor.observeRawRetention(2000);
|
||||
if (sizes.size() == 2) throw new IllegalStateException("DM unavailable");
|
||||
return null;
|
||||
}).when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
assertThrows(IllegalStateException.class, () -> processor.consumeAndParallelProcess(records(3000), ack));
|
||||
verifyNoInteractions(ack);
|
||||
assertEquals(Arrays.asList(500, 2500), sizes);
|
||||
sizes.clear();
|
||||
doAnswer(call -> { sizes.add(((List<?>) call.getArgument(0)).size()); return null; })
|
||||
.when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
processor.consumeAndParallelProcess(records(1000), ack);
|
||||
assertEquals(Arrays.asList(500, 500), sizes);
|
||||
}
|
||||
|
||||
@Test void feedbackDoesNotLeakAcrossConsumerThreadsOrChangeRetryAndLargeLanes() throws Exception {
|
||||
processor.observeRawRetention(1000);
|
||||
List<Integer> sizes = Collections.synchronizedList(new ArrayList<>());
|
||||
doAnswer(call -> { sizes.add(((List<?>) call.getArgument(0)).size()); return null; })
|
||||
.when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
ExecutorService otherConsumer = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
otherConsumer.submit(() -> processor.consumeAndParallelProcess(records(1000), ack)).get(3, TimeUnit.SECONDS);
|
||||
} finally { otherConsumer.shutdownNow(); }
|
||||
assertEquals(Arrays.asList(500, 500), sizes);
|
||||
sizes.clear();
|
||||
processor.consumeRetryAndReplay(records(1000), ack);
|
||||
processor.consumeLargeMessages(records(1000), ack);
|
||||
assertEquals(Arrays.asList(1000, 1000), sizes);
|
||||
}
|
||||
|
||||
@Test void staleFeedbackResetsAfterOneMinuteWithoutObservation() {
|
||||
processor.observeRawRetention(1000);
|
||||
Object state = ((ThreadLocal<?>) ReflectionTestUtils.getField(processor, "rawAdaptiveState")).get();
|
||||
ReflectionTestUtils.setField(state, "observedAt", System.nanoTime() - TimeUnit.MINUTES.toNanos(2));
|
||||
List<Integer> sizes = new ArrayList<>();
|
||||
doAnswer(call -> { sizes.add(((List<?>) call.getArgument(0)).size()); return null; })
|
||||
.when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
processor.consumeAndParallelProcess(records(1000), ack);
|
||||
assertEquals(Arrays.asList(500, 500), sizes);
|
||||
}
|
||||
|
||||
private List<ConsumerRecord<String, String>> records(int count) {
|
||||
List<ConsumerRecord<String, String>> result = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) result.add(new ConsumerRecord<>("raw", 0, i, "k", "value"));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+275
-1
@@ -8,12 +8,17 @@ import com.common.service.DeviceCollectTaskService;
|
||||
import com.common.service.DeviceDeviceService;
|
||||
import com.common.service.DmStandardizedBatchWriter;
|
||||
import com.common.service.SyslogNonNormalMessageService;
|
||||
import com.common.service.SyslogNormalDataService;
|
||||
import com.common.service.BacklogRetentionDelta;
|
||||
import com.config.BacklogSamplingProperties;
|
||||
import com.influx.raw.RawInfluxMetrics;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.kafka.support.Acknowledgment;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
@@ -21,6 +26,7 @@ import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -31,13 +37,17 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** 验证恢复并行后仍保留“全部可靠终态才允许返回”的处理边界。 */
|
||||
/** 验证批内并行、常规可靠路由及连续性优先的最终放行边界。 */
|
||||
class SysLogProcessorParallelTest {
|
||||
|
||||
private ExecutorService executor;
|
||||
@@ -47,16 +57,22 @@ class SysLogProcessorParallelTest {
|
||||
private SyslogFailureRouter failureRouter;
|
||||
private DmStandardizedBatchWriter batchWriter;
|
||||
private SyslogNonNormalMessageService nonNormalMessageService;
|
||||
private RawInfluxMetrics rawInfluxMetrics;
|
||||
private SyslogNormalDataService normalDataService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
executor = Executors.newFixedThreadPool(4);
|
||||
nonNormalExecutor = Executors.newSingleThreadExecutor();
|
||||
processor = new SysLogProcessor();
|
||||
ReflectionTestUtils.setField(processor, "rawLaneFieldLimiter",
|
||||
new com.common.service.RawLaneFieldLimiter(2048, "raw"));
|
||||
normalProcessor = mock(LogNormalProcessor.class);
|
||||
failureRouter = mock(SyslogFailureRouter.class);
|
||||
batchWriter = mock(DmStandardizedBatchWriter.class);
|
||||
nonNormalMessageService = mock(SyslogNonNormalMessageService.class);
|
||||
rawInfluxMetrics = mock(RawInfluxMetrics.class);
|
||||
normalDataService = mock(SyslogNormalDataService.class);
|
||||
ReflectionTestUtils.setField(processor, "taskExecutor", executor);
|
||||
ReflectionTestUtils.setField(processor, "processTimeoutMs", 5000L);
|
||||
ReflectionTestUtils.setField(processor, "logNormalProcessor", normalProcessor);
|
||||
@@ -66,6 +82,11 @@ class SysLogProcessorParallelTest {
|
||||
ReflectionTestUtils.setField(processor, "nonNormalWriterExecutor", nonNormalExecutor);
|
||||
ReflectionTestUtils.setField(processor, "nonNormalMaxConcurrencyRetries", 3);
|
||||
ReflectionTestUtils.setField(processor, "nonNormalConcurrencyRetryBackoffMs", 0L);
|
||||
ReflectionTestUtils.setField(processor, "failureContinuityEnabled", true);
|
||||
ReflectionTestUtils.setField(processor, "rawInfluxMetrics", rawInfluxMetrics);
|
||||
ReflectionTestUtils.setField(processor, "syslogNormalDataService", normalDataService);
|
||||
when(normalDataService.isAlarmData(any())).thenAnswer(invocation ->
|
||||
((java.util.Map<?, ?>) invocation.getArgument(0)).get("event_level") != null);
|
||||
when(batchWriter.write(any())).thenReturn(new DmStandardizedBatchWriter.WriteReport<>());
|
||||
when(normalProcessor.captureRuleSnapshot(any())).thenReturn(
|
||||
new BatchRuleSnapshot(Collections.emptyMap(), System.currentTimeMillis()));
|
||||
@@ -118,6 +139,32 @@ class SysLogProcessorParallelTest {
|
||||
() -> processor.normalizePreparedMessages(messages(2), metrics));
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentLargePollsSubmitOnlyBoundedWorkersAndProcessEveryRecord() throws Exception {
|
||||
AtomicInteger submissions = new AtomicInteger();
|
||||
Executor countedExecutor = task -> {
|
||||
submissions.incrementAndGet();
|
||||
executor.execute(task);
|
||||
};
|
||||
ReflectionTestUtils.setField(processor, "taskExecutor", countedExecutor);
|
||||
when(normalProcessor.prepare(any(PreparedNormalizationInput.class), any(), any(), any()))
|
||||
.thenReturn(LogNormalProcessor.NormalizationResult.success(
|
||||
Collections.singletonList(normalizedRow())));
|
||||
ExecutorService callers = Executors.newFixedThreadPool(3);
|
||||
try {
|
||||
List<java.util.concurrent.Future<?>> runs = new ArrayList<>();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
runs.add(callers.submit(() -> processor.normalizePreparedMessages(messages(3000),
|
||||
new SysLogProcessor.BatchMetrics())));
|
||||
}
|
||||
for (java.util.concurrent.Future<?> run : runs) run.get(10, TimeUnit.SECONDS);
|
||||
assertEquals(24, submissions.get(), "3个并发批次应提交24个worker,而非9000个任务");
|
||||
verify(normalProcessor, times(9000)).prepare(any(PreparedNormalizationInput.class), any(), any(), any());
|
||||
} finally {
|
||||
callers.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordsRuleComputeAndDmWriteTimingsSeparately() {
|
||||
when(normalProcessor.prepare(any(PreparedNormalizationInput.class), any(), any(), any()))
|
||||
@@ -232,6 +279,172 @@ class SysLogProcessorParallelTest {
|
||||
assertEquals(3, metrics.filteredCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unexpectedBatchFailureIsRecordedAndOffsetIsAcknowledged() {
|
||||
SysLogProcessor spyProcessor = spy(processor);
|
||||
RuntimeException sourceFailure = new IllegalStateException("unknown processing failure");
|
||||
doThrow(sourceFailure).when(spyProcessor)
|
||||
.processBatch(anyList(), eq(false), eq("RAW"), any(Executor.class));
|
||||
when(failureRouter.resolve(any())).thenAnswer(invocation -> {
|
||||
ConsumerRecord<String, String> record = invocation.getArgument(0);
|
||||
return new SyslogFailureRouter.MessageContext(record.value(), "event-" + record.offset(),
|
||||
0, null, Instant.now(), record.topic(), null);
|
||||
});
|
||||
when(failureRouter.routeContinuityDlt(any(), any(), eq(sourceFailure), eq("BATCH_RAW")))
|
||||
.thenReturn(SyslogFailureRouter.TerminalState.DLT_PUBLISHED);
|
||||
Acknowledgment ack = mock(Acknowledgment.class);
|
||||
|
||||
spyProcessor.consumeAndParallelProcess(records(2), ack);
|
||||
|
||||
verify(failureRouter, times(2))
|
||||
.routeContinuityDlt(any(), any(), eq(sourceFailure), eq("BATCH_RAW"));
|
||||
verify(rawInfluxMetrics).continuityDltPublished(2L);
|
||||
verify(ack).acknowledge();
|
||||
}
|
||||
|
||||
@Test
|
||||
void dltPublishFailureIsLoggedAndOffsetIsStillAcknowledged() {
|
||||
SysLogProcessor spyProcessor = spy(processor);
|
||||
RuntimeException sourceFailure = new IllegalStateException("unknown processing failure");
|
||||
doThrow(sourceFailure).when(spyProcessor)
|
||||
.processBatch(anyList(), eq(false), eq("RAW"), any(Executor.class));
|
||||
when(failureRouter.resolve(any())).thenAnswer(invocation -> {
|
||||
ConsumerRecord<String, String> record = invocation.getArgument(0);
|
||||
return new SyslogFailureRouter.MessageContext(record.value(), "event-" + record.offset(),
|
||||
0, null, Instant.now(), record.topic(), null);
|
||||
});
|
||||
when(failureRouter.routeContinuityDlt(any(), any(), eq(sourceFailure), eq("BATCH_RAW")))
|
||||
.thenThrow(new SyslogFailureRouter.FailurePublishException(
|
||||
"broker unavailable", new IllegalStateException("send failed")));
|
||||
Acknowledgment ack = mock(Acknowledgment.class);
|
||||
|
||||
spyProcessor.consumeAndParallelProcess(records(2), ack);
|
||||
|
||||
verify(failureRouter)
|
||||
.routeContinuityDlt(any(), any(), eq(sourceFailure), eq("BATCH_RAW"));
|
||||
verify(rawInfluxMetrics).continuityDltPublishFailed(2L);
|
||||
verify(ack).acknowledge();
|
||||
}
|
||||
|
||||
@Test
|
||||
void influxFailureNeverBlocksMainFlowEvenWhenGeneralContinuityIsDisabled() {
|
||||
SysLogProcessor spyProcessor = spy(processor);
|
||||
ReflectionTestUtils.setField(spyProcessor, "failureContinuityEnabled", false);
|
||||
RuntimeException influxFailure = new IllegalStateException("influx unavailable");
|
||||
doThrow(influxFailure).when(spyProcessor)
|
||||
.persistRawBatch(anyList(), any(SysLogProcessor.BatchMetrics.class));
|
||||
when(failureRouter.routeContinuityDlt(any(), any(), eq(influxFailure), eq("RAW_STORAGE")))
|
||||
.thenReturn(SyslogFailureRouter.TerminalState.DLT_PUBLISHED);
|
||||
List<SysLogProcessor.PreparedMessage> messages = messages(2);
|
||||
|
||||
List<SysLogProcessor.PreparedMessage> result = spyProcessor.persistRawWithoutBlockingMainFlow(
|
||||
messages, new SysLogProcessor.BatchMetrics(), "RAW");
|
||||
|
||||
assertEquals(messages, result);
|
||||
verify(failureRouter, times(2))
|
||||
.routeContinuityDlt(any(), any(), eq(influxFailure), eq("RAW_STORAGE"));
|
||||
verify(rawInfluxMetrics).rawWriteBypassed(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void influxAndDltDoubleFailureStillReturnsToMainFlow() {
|
||||
SysLogProcessor spyProcessor = spy(processor);
|
||||
RuntimeException influxFailure = new IllegalStateException("influx unavailable");
|
||||
doThrow(influxFailure).when(spyProcessor)
|
||||
.persistRawBatch(anyList(), any(SysLogProcessor.BatchMetrics.class));
|
||||
when(failureRouter.routeContinuityDlt(any(), any(), eq(influxFailure), eq("RAW_STORAGE")))
|
||||
.thenThrow(new SyslogFailureRouter.FailurePublishException(
|
||||
"broker unavailable", new IllegalStateException("send failed")));
|
||||
List<SysLogProcessor.PreparedMessage> messages = messages(2);
|
||||
|
||||
List<SysLogProcessor.PreparedMessage> result = spyProcessor.persistRawWithoutBlockingMainFlow(
|
||||
messages, new SysLogProcessor.BatchMetrics(), "RAW");
|
||||
|
||||
assertEquals(messages, result);
|
||||
verify(failureRouter).routeContinuityDlt(any(), any(), eq(influxFailure), eq("RAW_STORAGE"));
|
||||
verify(rawInfluxMetrics).continuityDltPublishFailed(2L);
|
||||
verify(rawInfluxMetrics).rawWriteBypassed(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void backlogSamplingKeepsAlarmAndDropsNormalAndNonNormalFromRawPlan() {
|
||||
BacklogSamplingProperties properties = new BacklogSamplingProperties();
|
||||
ReflectionTestUtils.setField(properties, "enabled", true);
|
||||
ReflectionTestUtils.setField(properties, "lagThresholdMs", 1L);
|
||||
ReflectionTestUtils.setField(properties, "normalRetainBps", 0);
|
||||
ReflectionTestUtils.setField(properties, "nonNormalRetainBps", 0);
|
||||
ReflectionTestUtils.setField(properties, "degradeSteps", 10);
|
||||
ReflectionTestUtils.setField(properties, "policyVersion", "test-v1");
|
||||
ReflectionTestUtils.setField(processor, "backlogSamplingDecider",
|
||||
new BacklogSamplingDecider(properties));
|
||||
|
||||
List<SysLogProcessor.PreparedMessage> source = oldMessages(3);
|
||||
java.util.Map<String, Object> alarm = normalizedRow();
|
||||
alarm.put("event_level", "HIGH");
|
||||
java.util.Map<String, Object> normal = normalizedRow();
|
||||
SyslogNonNormalMessage nonNormal = new SyslogNonNormalMessage();
|
||||
nonNormal.setId("non-normal");
|
||||
List<SysLogProcessor.PreparedNormalization> computed = new ArrayList<>();
|
||||
computed.add(new SysLogProcessor.PreparedNormalization(source.get(0),
|
||||
LogNormalProcessor.NormalizationResult.success(Collections.singletonList(alarm)), null));
|
||||
computed.add(new SysLogProcessor.PreparedNormalization(source.get(1),
|
||||
LogNormalProcessor.NormalizationResult.success(Collections.singletonList(normal)), null));
|
||||
computed.add(new SysLogProcessor.PreparedNormalization(source.get(2),
|
||||
LogNormalProcessor.NormalizationResult.filtered(Collections.singletonList(nonNormal)), null));
|
||||
|
||||
SysLogProcessor.SamplingPlan plan = processor.buildSamplingPlan(computed);
|
||||
|
||||
assertEquals(1, plan.rawMessageCount(), "只有告警原文必须保留");
|
||||
assertEquals(3, plan.auditMessageCount());
|
||||
long alarmSaved = 0L;
|
||||
long normalDropped = 0L;
|
||||
long nonNormalDropped = 0L;
|
||||
long rawDropped = 0L;
|
||||
for (BacklogRetentionDelta delta : plan.auditDeltas()) {
|
||||
alarmSaved += delta.getAlarmRowsSaved();
|
||||
normalDropped += delta.getNormalRowsDropped();
|
||||
nonNormalDropped += delta.getNonNormalRowsDropped();
|
||||
rawDropped += delta.getRawDropped();
|
||||
}
|
||||
assertEquals(1L, alarmSaved);
|
||||
assertEquals(1L, normalDropped);
|
||||
assertEquals(1L, nonNormalDropped);
|
||||
assertEquals(2L, rawDropped);
|
||||
assertEquals(0, plan.maxRetainBps());
|
||||
ReflectionTestUtils.setField(properties, "normalRetainBps", 1000);
|
||||
ReflectionTestUtils.setField(properties, "nonNormalRetainBps", 2000);
|
||||
assertEquals(2000, processor.buildSamplingPlan(computed).maxRetainBps(),
|
||||
"放大倍率必须使用两类中较高保留率");
|
||||
ReflectionTestUtils.setField(properties, "enabled", false);
|
||||
assertEquals(10000, processor.buildSamplingPlan(computed).maxRetainBps());
|
||||
ReflectionTestUtils.setField(properties, "enabled", true);
|
||||
computed.add(new SysLogProcessor.PreparedNormalization(source.get(0), null,
|
||||
SyslogFailureRouter.TerminalState.DLT_PUBLISHED));
|
||||
assertEquals(10000, processor.buildSamplingPlan(computed).maxRetainBps(),
|
||||
"规则结果未知时保守回到基础批量");
|
||||
computed.remove(computed.size() - 1);
|
||||
BacklogSamplingDecider mixed = mock(BacklogSamplingDecider.class);
|
||||
LocalDateTime hour = LocalDateTime.of(2026, 9, 13, 0, 0);
|
||||
BacklogSamplingDecision degraded = new BacklogSamplingDecision(true, true, true, true,
|
||||
3600000L, hour, "test", 1000, 2000);
|
||||
BacklogSamplingDecision recent = new BacklogSamplingDecision(false, true, true, true,
|
||||
0L, hour, "test", 10000, 10000);
|
||||
when(mixed.decide(any(), any(), org.mockito.ArgumentMatchers.anyBoolean(),
|
||||
org.mockito.ArgumentMatchers.anyBoolean(), org.mockito.ArgumentMatchers.anyBoolean()))
|
||||
.thenReturn(degraded, recent, degraded);
|
||||
ReflectionTestUtils.setField(processor, "backlogSamplingDecider", mixed);
|
||||
assertEquals(10000, processor.buildSamplingPlan(computed).maxRetainBps(),
|
||||
"同块包含新旧不同阶段消息时取最高保留率");
|
||||
}
|
||||
|
||||
private List<ConsumerRecord<String, String>> records(int count) {
|
||||
List<ConsumerRecord<String, String>> records = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
records.add(new ConsumerRecord<>("raw", 0, i, "key-" + i, "ciphertext-" + i));
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
private List<SysLogProcessor.PreparedMessage> messages(int count) {
|
||||
List<SysLogProcessor.PreparedMessage> messages = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
@@ -248,6 +461,67 @@ class SysLogProcessorParallelTest {
|
||||
return messages;
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void rawOutputIsLimitedAfterRulesAndLargeOutputIsUnchangedIncludingRetry() {
|
||||
for (String originalTopic : java.util.Arrays.asList("raw", "raw.large")) {
|
||||
ConsumerRecord<String, String> record = new ConsumerRecord<>("retry", 0, 0L, "key", "ciphertext");
|
||||
SyslogFailureRouter.MessageContext context = new SyslogFailureRouter.MessageContext(
|
||||
"ciphertext", "stable-id", 1, null, Instant.EPOCH, originalTopic, null);
|
||||
String content = String.join("", Collections.nCopies(3000, "中"));
|
||||
SysLogProcessor.PreparedMessage source = new SysLogProcessor.PreparedMessage(record, context,
|
||||
content, "stable-id", null, LocalDateTime.now(), 7L, 3L, System.currentTimeMillis());
|
||||
java.util.Map<String, Object> normal = normalizedRow();
|
||||
normal.put("custom_field", content);
|
||||
java.util.Map<String, Object> alarm = normalizedRow();
|
||||
alarm.put("event_level", "HIGH");
|
||||
alarm.put("description", content);
|
||||
SyslogNonNormalMessage nonNormal = new SyslogNonNormalMessage();
|
||||
nonNormal.setSyslogMessage(content);
|
||||
List<SysLogProcessor.PreparedNormalization> computed = java.util.Arrays.asList(
|
||||
new SysLogProcessor.PreparedNormalization(source,
|
||||
LogNormalProcessor.NormalizationResult.success(java.util.Arrays.asList(normal, alarm)), null),
|
||||
new SysLogProcessor.PreparedNormalization(source,
|
||||
LogNormalProcessor.NormalizationResult.filtered(Collections.singletonList(nonNormal)), null));
|
||||
Object retainedPlan = ReflectionTestUtils.invokeMethod(processor, "allRetainedPlan", computed);
|
||||
Object persistencePlan = ReflectionTestUtils.invokeMethod(processor, "prepareStandardizedPersistence",
|
||||
ReflectionTestUtils.getField(retainedPlan, "normalizations"), new SysLogProcessor.BatchMetrics());
|
||||
for (String requestsName : java.util.Arrays.asList("normalWriteRequests", "alarmWriteRequests")) {
|
||||
List<DmStandardizedBatchWriter.WriteRequest<SysLogProcessor.PreparedMessage>> requests =
|
||||
(List<DmStandardizedBatchWriter.WriteRequest<SysLogProcessor.PreparedMessage>>)
|
||||
ReflectionTestUtils.getField(persistencePlan, requestsName);
|
||||
assertEquals(1, requests.size(), "告警和普通记录数量不变");
|
||||
String stored = (String) requests.get(0).getData().get(
|
||||
"alarmWriteRequests".equals(requestsName) ? "description" : "custom_field");
|
||||
if ("raw".equals(originalTopic) && "normalWriteRequests".equals(requestsName)) {
|
||||
assertTrue(stored.getBytes(java.nio.charset.StandardCharsets.UTF_8).length <= 2048);
|
||||
assertTrue(stored.contains("HB_XDR_TRUNCATED"));
|
||||
} else {
|
||||
assertEquals(content, stored);
|
||||
}
|
||||
}
|
||||
assertEquals(content, normal.get("custom_field"), "规则计算结果不被原地覆盖");
|
||||
assertEquals(content, alarm.get("description"));
|
||||
assertEquals(content, ReflectionTestUtils.getField(source, "decryptedMessage"), "Influx原文不改变");
|
||||
if ("raw".equals(originalTopic)) assertTrue(nonNormal.getSyslogMessage().contains("HB_XDR_TRUNCATED"));
|
||||
else assertEquals(content, nonNormal.getSyslogMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private List<SysLogProcessor.PreparedMessage> oldMessages(int count) {
|
||||
List<SysLogProcessor.PreparedMessage> old = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
ConsumerRecord<String, String> record =
|
||||
new ConsumerRecord<>("raw", i % 2, i, "key-" + i, "ciphertext");
|
||||
SyslogFailureRouter.MessageContext context = new SyslogFailureRouter.MessageContext(
|
||||
"ciphertext", "old-event-" + i, 0, null, Instant.EPOCH);
|
||||
old.add(new SysLogProcessor.PreparedMessage(record, context, "message-" + i,
|
||||
"old-event-" + i, null, LocalDateTime.of(2000, 1, 1, 0, 0),
|
||||
7L, 3L, System.currentTimeMillis()));
|
||||
}
|
||||
return old;
|
||||
}
|
||||
|
||||
private java.util.Map<String, Object> normalizedRow() {
|
||||
java.util.Map<String, Object> row = new java.util.HashMap<>();
|
||||
row.put("id", java.util.UUID.randomUUID().toString());
|
||||
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package com.Modules.NormalData;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.kafka.support.Acknowledgment;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.stream.Collectors;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
class SysLogSlowBatchTraceTest {
|
||||
private final Logger logger = (Logger) LoggerFactory.getLogger(SysLogProcessor.class);
|
||||
private ListAppender<ILoggingEvent> appender;
|
||||
private SysLogProcessor processor;
|
||||
|
||||
@BeforeEach void setup() {
|
||||
appender = new ListAppender<>();
|
||||
appender.start();
|
||||
logger.addAppender(appender);
|
||||
processor = spy(new SysLogProcessor());
|
||||
ReflectionTestUtils.setField(processor, "taskExecutor", (Executor) Runnable::run);
|
||||
ReflectionTestUtils.setField(processor, "slowBatchThresholdMs", 1L);
|
||||
ReflectionTestUtils.setField(processor, "failureContinuityEnabled", false);
|
||||
MDC.put("syslogBatchId", "previous-context");
|
||||
}
|
||||
|
||||
@AfterEach void cleanup() {
|
||||
logger.detachAppender(appender);
|
||||
appender.stop();
|
||||
MDC.remove("syslogBatchId");
|
||||
}
|
||||
|
||||
@Test void successfulTraceContainsStageBreakdownOffsetsAndRestoresContext() {
|
||||
doAnswer(call -> {
|
||||
ReflectionTestUtils.invokeMethod(processor, "enterStage", "PREPARE");
|
||||
Object trace = trace();
|
||||
ReflectionTestUtils.setField(trace, "startedAtNanos", System.nanoTime() - 10_000_000L);
|
||||
ReflectionTestUtils.setField(trace, "stageStarted", System.nanoTime() - 2_000_000L);
|
||||
ReflectionTestUtils.invokeMethod(processor, "enterStage", "ALARM_DM");
|
||||
return null;
|
||||
}).when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
Acknowledgment ack = mock(Acknowledgment.class);
|
||||
processor.consumeAndParallelProcess(records(), ack);
|
||||
verify(ack).acknowledge();
|
||||
String log = onlyTrace();
|
||||
assertTrue(log.contains("PREPARE="));
|
||||
assertTrue(log.contains("ADAPTIVE_CHUNK_SELECTION="));
|
||||
assertTrue(log.contains("adaptiveTargetHistogram={3000=1}"));
|
||||
assertTrue(log.contains("actualChunkHistogram={2=1}"));
|
||||
assertTrue(log.contains("ALARM_DM="));
|
||||
assertTrue(log.contains("raw:0=12..14"));
|
||||
assertTrue(log.contains("kafkaCommitStatus=SUCCESS"));
|
||||
assertTrue(log.contains("listenerGapMs=-1"));
|
||||
assertFalse(log.contains("batchId=previous-context"));
|
||||
assertEquals("previous-context", MDC.get("syslogBatchId"));
|
||||
assertNull(trace());
|
||||
}
|
||||
|
||||
@Test void businessAbortReportsFailingStageAndNoCommitInsteadOfFalseSuccess() {
|
||||
doAnswer(call -> {
|
||||
ReflectionTestUtils.invokeMethod(processor, "enterStage", "NORMAL_DM");
|
||||
throw new IllegalStateException("DB stalled");
|
||||
}).when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
Acknowledgment ack = mock(Acknowledgment.class);
|
||||
assertThrows(IllegalStateException.class, () -> processor.consumeAndParallelProcess(records(), ack));
|
||||
verifyNoInteractions(ack);
|
||||
String log = onlyTrace();
|
||||
assertTrue(log.contains("failureStage=NORMAL_DM"));
|
||||
assertTrue(log.contains("kafkaCommitStatus=NOT_ATTEMPTED"));
|
||||
assertTrue(log.contains("failedChunks=1"));
|
||||
assertEquals("previous-context", MDC.get("syslogBatchId"));
|
||||
}
|
||||
|
||||
@Test void commitFailureIsLoggedExactlyOnce() {
|
||||
doNothing().when(processor).processBatch(anyList(), anyBoolean(), anyString(), any());
|
||||
Acknowledgment ack = mock(Acknowledgment.class);
|
||||
doThrow(new IllegalStateException("commit rejected")).when(ack).acknowledge();
|
||||
assertThrows(IllegalStateException.class, () -> processor.consumeAndParallelProcess(records(), ack));
|
||||
String log = onlyTrace();
|
||||
assertTrue(log.contains("kafkaCommitStatus=FAILED"));
|
||||
assertTrue(log.contains("kafkaCommitErrorType=java.lang.IllegalStateException"));
|
||||
assertEquals("previous-context", MDC.get("syslogBatchId"));
|
||||
}
|
||||
|
||||
private Object trace() {
|
||||
return ((ThreadLocal<?>) ReflectionTestUtils.getField(processor, "slowBatchTrace")).get();
|
||||
}
|
||||
private String onlyTrace() {
|
||||
List<String> logs = appender.list.stream().map(ILoggingEvent::getFormattedMessage)
|
||||
.filter(line -> line.contains("[SLOW_SYSLOG_BATCH]")).collect(Collectors.toList());
|
||||
assertEquals(1, logs.size());
|
||||
assertFalse(logs.get(0).contains("batchId={}"));
|
||||
return logs.get(0);
|
||||
}
|
||||
private List<ConsumerRecord<String, String>> records() {
|
||||
return Arrays.asList(new ConsumerRecord<>("raw", 0, 12L, "k", "first"),
|
||||
new ConsumerRecord<>("raw", 0, 14L, "k", "second"));
|
||||
}
|
||||
}
|
||||
+56
@@ -42,6 +42,11 @@ class SyslogFailureRouterReliabilityTest {
|
||||
ReflectionTestUtils.setField(router, "retry10mTopic", "raw.RETRY.10M");
|
||||
ReflectionTestUtils.setField(router, "retry1hTopic", "raw.RETRY.1H");
|
||||
ReflectionTestUtils.setField(router, "dltTopic", "raw.DLT");
|
||||
ReflectionTestUtils.setField(router, "largeOriginalTopic", "raw.large");
|
||||
ReflectionTestUtils.setField(router, "largeRetry1mTopic", "raw.large.RETRY.1M");
|
||||
ReflectionTestUtils.setField(router, "largeRetry10mTopic", "raw.large.RETRY.10M");
|
||||
ReflectionTestUtils.setField(router, "largeRetry1hTopic", "raw.large.RETRY.1H");
|
||||
ReflectionTestUtils.setField(router, "largeDltTopic", "raw.large.DLT");
|
||||
ReflectionTestUtils.setField(router, "publishTimeoutMs", 1000L);
|
||||
ReflectionTestUtils.setField(router, "consumerVersion", "test");
|
||||
record = new ConsumerRecord<>("raw", 2, 42L, "device-1", "ciphertext");
|
||||
@@ -86,6 +91,22 @@ class SyslogFailureRouterReliabilityTest {
|
||||
assertFalse(body.getValue().contains("schema_version"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void largeMessageFailureNeverFallsBackIntoNormalRetryTopic() {
|
||||
ConsumerRecord<String, String> largeRecord = new ConsumerRecord<>(
|
||||
"raw.large", 1, 7L, "event", "large-ciphertext");
|
||||
SettableListenableFuture<SendResult<String, String>> acknowledged = new SettableListenableFuture<>();
|
||||
acknowledged.set(null);
|
||||
when(template.send(eq("raw.large.RETRY.1M"), anyString(), anyString()))
|
||||
.thenReturn(acknowledged);
|
||||
|
||||
SyslogFailureRouter.TerminalState state = router.route(
|
||||
largeRecord, router.resolve(largeRecord), new SocketException("reset"));
|
||||
|
||||
assertEquals(SyslogFailureRouter.TerminalState.RETRY_PUBLISHED, state);
|
||||
verify(template).send(eq("raw.large.RETRY.1M"), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishFailureNeverBecomesTerminal() {
|
||||
SettableListenableFuture<SendResult<String, String>> failed = new SettableListenableFuture<>();
|
||||
@@ -96,6 +117,41 @@ class SyslogFailureRouterReliabilityTest {
|
||||
() -> router.route(record, router.resolve(record), new SocketException("reset")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void continuityFailureIsWrittenDirectlyToDltWithOriginalPayload() throws Exception {
|
||||
SettableListenableFuture<SendResult<String, String>> acknowledged = new SettableListenableFuture<>();
|
||||
acknowledged.set(null);
|
||||
when(template.send(eq("raw.DLT"), anyString(), anyString())).thenReturn(acknowledged);
|
||||
ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
SyslogFailureRouter.TerminalState state = router.routeContinuityDlt(
|
||||
record, router.resolve(record), new InfluxException("influx unavailable"), "RAW_STORAGE");
|
||||
|
||||
assertEquals(SyslogFailureRouter.TerminalState.DLT_PUBLISHED, state);
|
||||
verify(template).send(eq("raw.DLT"), anyString(), body.capture());
|
||||
SyslogFailureRouter.FailureEnvelope envelope = new ObjectMapper().findAndRegisterModules()
|
||||
.readValue(body.getValue(), SyslogFailureRouter.FailureEnvelope.class);
|
||||
assertEquals("SYSLOG_CONTINUITY_BYPASS", envelope.getErrorCode());
|
||||
assertEquals("RAW_STORAGE", envelope.getFailedStage());
|
||||
assertEquals("ciphertext", envelope.getOriginalPayload());
|
||||
assertEquals("raw", envelope.getOriginalTopic());
|
||||
assertEquals(42L, envelope.getOriginalOffset());
|
||||
}
|
||||
|
||||
@Test
|
||||
void continuityFailureFromLargeLaneUsesLargeDlt() {
|
||||
ConsumerRecord<String, String> largeRecord = new ConsumerRecord<>(
|
||||
"raw.large", 1, 7L, "event", "large-ciphertext");
|
||||
SettableListenableFuture<SendResult<String, String>> acknowledged = new SettableListenableFuture<>();
|
||||
acknowledged.set(null);
|
||||
when(template.send(eq("raw.large.DLT"), anyString(), anyString())).thenReturn(acknowledged);
|
||||
|
||||
router.routeContinuityDlt(largeRecord, router.resolve(largeRecord),
|
||||
new IllegalStateException("unknown"), "BATCH_RAW_LARGE");
|
||||
|
||||
verify(template).send(eq("raw.large.DLT"), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void influxDependencyFailurePausesWithoutDltStorm() {
|
||||
SyslogFailureRouter.TerminalState state = router.route(
|
||||
|
||||
+71
@@ -4,12 +4,17 @@ import org.junit.jupiter.api.Test;
|
||||
import org.springframework.kafka.annotation.KafkaListener;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import com.common.service.StatsMaterializationConsumer;
|
||||
import com.common.service.StatsProjectionDeltaConsumer;
|
||||
|
||||
/** 防止多节点 consumer-rule 的监听器 ID 或显式消费组在后续合并中回退。 */
|
||||
class SyslogKafkaTopologyTest {
|
||||
@@ -50,6 +55,56 @@ class SyslogKafkaTopologyTest {
|
||||
}, listener.topics());
|
||||
}
|
||||
|
||||
@Test
|
||||
void largeRawListenerUsesDedicatedTopicGroupAndFactory() throws Exception {
|
||||
Method method = SysLogProcessor.class.getMethod(
|
||||
"consumeLargeMessages", List.class,
|
||||
org.springframework.kafka.support.Acknowledgment.class);
|
||||
KafkaListener listener = method.getAnnotation(KafkaListener.class);
|
||||
|
||||
assertNotNull(listener);
|
||||
assertEquals("syslog-consumer-rule-raw-large", listener.id());
|
||||
assertEquals("${syslog.large-listener.group-id:${spring.kafka.consumer.group-id}-large}",
|
||||
listener.groupId());
|
||||
assertEquals("largeRawKafkaListenerContainerFactory", listener.containerFactory());
|
||||
assertArrayEquals(new String[]{"${spring.kafka.consumer.large-topic:agent-syslog-topic.large}"},
|
||||
listener.topics());
|
||||
}
|
||||
|
||||
@Test
|
||||
void largeRetryReplayListenerIsAlsoIsolated() throws Exception {
|
||||
Method method = SysLogProcessor.class.getMethod(
|
||||
"consumeLargeRetryAndReplay", List.class,
|
||||
org.springframework.kafka.support.Acknowledgment.class);
|
||||
KafkaListener listener = method.getAnnotation(KafkaListener.class);
|
||||
|
||||
assertNotNull(listener);
|
||||
assertEquals("syslog-consumer-rule-large-retry-replay", listener.id());
|
||||
assertEquals("largeRawKafkaListenerContainerFactory", listener.containerFactory());
|
||||
assertArrayEquals(new String[]{
|
||||
"${syslog.large-reliability.retry-1m-topic:${spring.kafka.consumer.large-topic}.RETRY.1M}",
|
||||
"${syslog.large-reliability.retry-10m-topic:${spring.kafka.consumer.large-topic}.RETRY.10M}",
|
||||
"${syslog.large-reliability.retry-1h-topic:${spring.kafka.consumer.large-topic}.RETRY.1H}",
|
||||
"${syslog.large-reliability.replay-topic:${spring.kafka.consumer.large-topic}.REPLAY}"
|
||||
}, listener.topics());
|
||||
}
|
||||
|
||||
@Test
|
||||
void largePollIsPartitionedByUtf8BytesInsteadOfOnlyRecordCount() {
|
||||
List<ConsumerRecord<String, String>> records = Arrays.asList(
|
||||
new ConsumerRecord<>("large", 0, 0L, "k1", "中文"),
|
||||
new ConsumerRecord<>("large", 0, 1L, "k2", "12"),
|
||||
new ConsumerRecord<>("large", 0, 2L, "k3", "🙂"));
|
||||
|
||||
List<List<ConsumerRecord<String, String>>> chunks =
|
||||
SysLogProcessor.partitionRecordsByBytes(records, 7L);
|
||||
|
||||
assertEquals(2, chunks.size());
|
||||
assertEquals(1, chunks.get(0).size());
|
||||
assertEquals(2, chunks.get(1).size());
|
||||
assertEquals(6, chunks.get(0).get(0).value().getBytes(StandardCharsets.UTF_8).length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void statsMaterializerUsesDedicatedTopicAndGroup() throws Exception {
|
||||
Method method = StatsMaterializationConsumer.class.getMethod(
|
||||
@@ -65,4 +120,20 @@ class SyslogKafkaTopologyTest {
|
||||
"${stats.materialization.topic:${spring.kafka.consumer.topic}.STATS.MATERIALIZE}"
|
||||
}, listener.topics());
|
||||
}
|
||||
|
||||
@Test
|
||||
void statsProjectionUsesSeparateSingleLaneTopicAndGroup() throws Exception {
|
||||
Method method = StatsProjectionDeltaConsumer.class.getMethod(
|
||||
"consume", List.class, org.springframework.kafka.support.Acknowledgment.class);
|
||||
KafkaListener listener = method.getAnnotation(KafkaListener.class);
|
||||
|
||||
assertNotNull(listener);
|
||||
assertEquals("syslog-stats-projection", listener.id());
|
||||
assertEquals("${stats.projection-async.group-id:${spring.kafka.consumer.group-id}-stats-projection}",
|
||||
listener.groupId());
|
||||
assertEquals("statsProjectionKafkaListenerContainerFactory", listener.containerFactory());
|
||||
assertArrayEquals(new String[]{
|
||||
"${stats.projection-async.topic:${spring.kafka.consumer.topic}.STATS.PROJECTION}"
|
||||
}, listener.topics());
|
||||
}
|
||||
}
|
||||
|
||||
+18
@@ -10,6 +10,8 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
class NormalizationCacheInvalidationServiceTest {
|
||||
@Test
|
||||
void evictsMatchingLegacyAndJetCacheKeys() {
|
||||
@@ -35,4 +37,20 @@ class NormalizationCacheInvalidationServiceTest {
|
||||
verify(jet).collectTask(8);
|
||||
verify(jet).rulesForDevice(9L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearsOnlyRuleSpringCacheAndBroadcastsEveryDevice() {
|
||||
CacheManager manager = mock(CacheManager.class);
|
||||
Cache rules = mock(Cache.class);
|
||||
when(manager.getCache("normalizeRule")).thenReturn(rules);
|
||||
NormalizationCacheInvalidator jet = mock(NormalizationCacheInvalidator.class);
|
||||
NormalizationCacheInvalidationService service = new NormalizationCacheInvalidationService(
|
||||
manager, jet, new NormalizationRuleMetrics());
|
||||
|
||||
service.invalidateAllRules(Arrays.asList(9L, null, 10L));
|
||||
|
||||
verify(rules).clear();
|
||||
verify(jet).rulesForDevice(9L);
|
||||
verify(jet).rulesForDevice(10L);
|
||||
}
|
||||
}
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.Modules.NormalData.compiled.CompiledRuleCache;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.data.redis.connection.DefaultMessage;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class NormalizationCompiledCacheInvalidationBusTest {
|
||||
|
||||
@Test
|
||||
void clearsLocalRulesAndPublishesOneClusterCommand() {
|
||||
CompiledRuleCache cache = mock(CompiledRuleCache.class);
|
||||
StringRedisTemplate redis = mock(StringRedisTemplate.class);
|
||||
NormalizationCompiledCacheInvalidationBus bus =
|
||||
new NormalizationCompiledCacheInvalidationBus(cache, redis);
|
||||
|
||||
bus.invalidateRulesEverywhere(Arrays.asList(7L, 8L, 8L, null));
|
||||
|
||||
verify(cache).invalidateRule(7L);
|
||||
verify(cache).invalidateRule(8L);
|
||||
verify(redis).convertAndSend(
|
||||
NormalizationCompiledCacheInvalidationBus.TOPIC, "RULES:7,8");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearsAllLocallyAndPublishesClusterCommand() {
|
||||
CompiledRuleCache cache = mock(CompiledRuleCache.class);
|
||||
StringRedisTemplate redis = mock(StringRedisTemplate.class);
|
||||
NormalizationCompiledCacheInvalidationBus bus =
|
||||
new NormalizationCompiledCacheInvalidationBus(cache, redis);
|
||||
|
||||
bus.invalidateAllEverywhere();
|
||||
|
||||
verify(cache).invalidateAll();
|
||||
verify(redis).convertAndSend(
|
||||
NormalizationCompiledCacheInvalidationBus.TOPIC, "ALL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void subscriberClearsCompiledCacheOnEveryInstance() {
|
||||
CompiledRuleCache cache = mock(CompiledRuleCache.class);
|
||||
NormalizationCompiledCacheInvalidationBus bus =
|
||||
new NormalizationCompiledCacheInvalidationBus(
|
||||
cache, mock(StringRedisTemplate.class));
|
||||
|
||||
bus.onMessage(message("RULES:7,8"), null);
|
||||
bus.onMessage(message("ALL"), null);
|
||||
|
||||
verify(cache).invalidateRule(7L);
|
||||
verify(cache).invalidateRule(8L);
|
||||
verify(cache).invalidateAll();
|
||||
}
|
||||
|
||||
private static DefaultMessage message(String body) {
|
||||
return new DefaultMessage(
|
||||
NormalizationCompiledCacheInvalidationBus.TOPIC.getBytes(StandardCharsets.UTF_8),
|
||||
body.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.common.mapper.DeviceDeviceMapper;
|
||||
import com.common.mapper.DmNormalizeRuleMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class NormalizationRuleCacheManagementServiceTest {
|
||||
|
||||
@Test
|
||||
void clearsDeviceRuleViewsEntitiesAndCompiledRules() {
|
||||
NormalizationCacheInvalidationService invalidation =
|
||||
mock(NormalizationCacheInvalidationService.class);
|
||||
NormalizationCompiledCacheInvalidationBus compiled =
|
||||
mock(NormalizationCompiledCacheInvalidationBus.class);
|
||||
DeviceDeviceMapper devices = mock(DeviceDeviceMapper.class);
|
||||
DmNormalizeRuleMapper rules = mock(DmNormalizeRuleMapper.class);
|
||||
when(rules.selectRuleIdsByDeviceId(40L)).thenReturn(Arrays.asList(7L, 8L, 8L));
|
||||
NormalizationRuleCacheManagementService service =
|
||||
new NormalizationRuleCacheManagementService(invalidation, compiled, devices, rules);
|
||||
|
||||
NormalizationRuleCacheManagementService.ClearResult result = service.clearDevice(40L);
|
||||
|
||||
assertEquals("DEVICE", result.getScope());
|
||||
assertEquals(40L, result.getDeviceId());
|
||||
assertEquals(2, result.getAssociatedRuleCount());
|
||||
verify(invalidation).invalidateRulesForDevice(40L);
|
||||
verify(invalidation).invalidateRuleEntity(7L);
|
||||
verify(invalidation).invalidateRuleEntity(8L);
|
||||
verify(compiled).invalidateRulesEverywhere(
|
||||
new java.util.LinkedHashSet<>(Arrays.asList(7L, 8L)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearsAllDistinctDeviceViewsAndCompiledCache() {
|
||||
NormalizationCacheInvalidationService invalidation =
|
||||
mock(NormalizationCacheInvalidationService.class);
|
||||
NormalizationCompiledCacheInvalidationBus compiled =
|
||||
mock(NormalizationCompiledCacheInvalidationBus.class);
|
||||
DeviceDeviceMapper devices = mock(DeviceDeviceMapper.class);
|
||||
DmNormalizeRuleMapper rules = mock(DmNormalizeRuleMapper.class);
|
||||
when(devices.selectAllIds()).thenReturn(Arrays.asList(40L, 41L));
|
||||
when(rules.selectAllAssociatedDeviceIds()).thenReturn(Arrays.asList(41L, 42L));
|
||||
NormalizationRuleCacheManagementService service =
|
||||
new NormalizationRuleCacheManagementService(invalidation, compiled, devices, rules);
|
||||
|
||||
NormalizationRuleCacheManagementService.ClearResult result = service.clearAll();
|
||||
|
||||
assertEquals("ALL", result.getScope());
|
||||
assertEquals(3, result.getDeviceCount());
|
||||
verify(invalidation).invalidateAllRules(
|
||||
org.mockito.ArgumentMatchers.argThat(ids -> ids.equals(
|
||||
new java.util.LinkedHashSet<>(Arrays.asList(40L, 41L, 42L)))));
|
||||
verify(compiled).invalidateAllEverywhere();
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsDeviceWithoutAssociatedRules() {
|
||||
NormalizationCacheInvalidationService invalidation =
|
||||
mock(NormalizationCacheInvalidationService.class);
|
||||
NormalizationCompiledCacheInvalidationBus compiled =
|
||||
mock(NormalizationCompiledCacheInvalidationBus.class);
|
||||
DeviceDeviceMapper devices = mock(DeviceDeviceMapper.class);
|
||||
DmNormalizeRuleMapper rules = mock(DmNormalizeRuleMapper.class);
|
||||
when(rules.selectRuleIdsByDeviceId(40L)).thenReturn(Collections.emptyList());
|
||||
NormalizationRuleCacheManagementService service =
|
||||
new NormalizationRuleCacheManagementService(invalidation, compiled, devices, rules);
|
||||
|
||||
assertEquals(0, service.clearDevice(40L).getAssociatedRuleCount());
|
||||
verify(invalidation).invalidateRulesForDevice(40L);
|
||||
}
|
||||
}
|
||||
+18
@@ -101,6 +101,24 @@ class CompiledRuleCacheTest {
|
||||
assertEquals(4, compiler.compiles.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidatingAllRemovesEveryCompiledRule() {
|
||||
CountingCompiler compiler = new CountingCompiler();
|
||||
CompiledRuleCache cache = new CompiledRuleCache(compiler, properties());
|
||||
RuleSource first = source("v1", "{\"mappers\":[]}");
|
||||
RuleSource second = new RuleSource(9L, "rule-9", "rule-9", "json",
|
||||
"{\"mappers\":[]}", true, "0");
|
||||
cache.get(first, null);
|
||||
cache.get(second, null);
|
||||
assertEquals(2, compiler.compiles.get());
|
||||
|
||||
cache.invalidateAll();
|
||||
assertEquals(0L, cache.estimatedSize());
|
||||
cache.get(first, null);
|
||||
cache.get(second, null);
|
||||
assertEquals(4, compiler.compiles.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void diagnosticRuleTextKeepsExecutionFieldsAndRemovesEmbeddedSamples() {
|
||||
String diagnostic = CompiledRuleCache.diagnosticRuleText("{"
|
||||
|
||||
+13
-3
@@ -110,7 +110,7 @@ class CompiledRuleCompilerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void decodesStringMappersButIgnoresStringFiltersAndCompletionsLikeLegacy() {
|
||||
void decodesStringMappersFiltersAndCompletionsLikeLegacyFastjsonAccessors() {
|
||||
RuleSource legacyShape = source(1996235894300086273L, "embedded-json", "json", "{"
|
||||
+ "\"mappers\":\"[{\\\"origin_field\\\":\\\"src\\\","
|
||||
+ "\\\"dest_field\\\":\\\"dest\\\","
|
||||
@@ -124,8 +124,18 @@ class CompiledRuleCompilerTest {
|
||||
CompiledRule compiled = compiler.compile(legacyShape);
|
||||
|
||||
assertEquals(1, compiled.getMapperByOriginField().get("src").size());
|
||||
assertTrue(compiled.getFilters().isEmpty());
|
||||
assertTrue(compiled.getCompletions().isEmpty());
|
||||
assertEquals(1, compiled.getFilters().size());
|
||||
assertEquals(1, compiled.getCompletions().size());
|
||||
|
||||
Map<String, Object> allowed = new java.util.LinkedHashMap<>();
|
||||
allowed.put("dest", "allowed");
|
||||
assertFalse(compiled.isFiltered(allowed));
|
||||
compiled.complete(allowed);
|
||||
assertEquals("CN", allowed.get("country"));
|
||||
|
||||
Map<String, Object> blocked = new java.util.LinkedHashMap<>();
|
||||
blocked.put("dest", "blocked");
|
||||
assertTrue(compiled.isFiltered(blocked));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.common.mapper;
|
||||
|
||||
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
|
||||
import org.apache.ibatis.session.Configuration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class NormalizationRuleCacheMapperXmlTest {
|
||||
|
||||
@Test
|
||||
void mapperXmlContainsCacheManagementQueries() throws Exception {
|
||||
Configuration configuration = new Configuration();
|
||||
parse(configuration, "mapper/DeviceDeviceMapper.xml");
|
||||
parse(configuration, "mapper/DmNormalizeRuleMapper.xml");
|
||||
|
||||
assertTrue(configuration.hasStatement(
|
||||
"com.common.mapper.DeviceDeviceMapper.selectAllIds"));
|
||||
assertTrue(configuration.hasStatement(
|
||||
"com.common.mapper.DmNormalizeRuleMapper.selectRuleIdsByDeviceId"));
|
||||
assertTrue(configuration.hasStatement(
|
||||
"com.common.mapper.DmNormalizeRuleMapper.selectAllAssociatedDeviceIds"));
|
||||
}
|
||||
|
||||
private static void parse(Configuration configuration, String resource) throws Exception {
|
||||
try (InputStream stream = Thread.currentThread().getContextClassLoader()
|
||||
.getResourceAsStream(resource)) {
|
||||
assertNotNull(stream, resource);
|
||||
new XMLMapperBuilder(stream, configuration, resource,
|
||||
configuration.getSqlFragments()).parse();
|
||||
}
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.mapper.BacklogRetentionAuditMapper;
|
||||
import com.config.BacklogSamplingProperties;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.TransactionStatus;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class BacklogSamplingAuditServiceTest {
|
||||
|
||||
@Test
|
||||
void aggregatesSameHourTopicPartitionAndPolicyWithoutMutatingInput() {
|
||||
BacklogRetentionDelta first = delta(1, 1, 0, 1, 0);
|
||||
BacklogRetentionDelta second = delta(1, 0, 1, 0, 1);
|
||||
|
||||
List<BacklogRetentionDelta> result = BacklogSamplingAuditService.aggregate(
|
||||
Arrays.asList(first, second));
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(2L, result.get(0).getMessageTotal());
|
||||
assertEquals(1L, result.get(0).getNormalRowsSaved());
|
||||
assertEquals(1L, result.get(0).getNormalRowsDropped());
|
||||
assertEquals(1L, result.get(0).getRawSaved());
|
||||
assertEquals(1L, result.get(0).getRawDropped());
|
||||
assertEquals(1L, first.getMessageTotal(), "聚合不能修改调用方的逐消息审计对象");
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditFailureIsBackgroundOnlyAndNeverTriggersFullRetentionFallback() {
|
||||
BacklogRetentionAuditMapper mapper = mock(BacklogRetentionAuditMapper.class);
|
||||
when(mapper.upsert(any())).thenThrow(new IllegalStateException("table unavailable"));
|
||||
PlatformTransactionManager transactionManager = transactionManager();
|
||||
BacklogSamplingMetrics metrics = new BacklogSamplingMetrics();
|
||||
BacklogSamplingAuditService service = new BacklogSamplingAuditService(
|
||||
mapper, properties(), metrics, transactionManager);
|
||||
|
||||
boolean audited = service.recordAsync(Arrays.asList(
|
||||
delta(2, 1, 1, 1, 1)));
|
||||
|
||||
assertTrue(audited);
|
||||
org.mockito.Mockito.verifyNoInteractions(mapper, transactionManager);
|
||||
((BestEffortAuxiliaryQueue) ReflectionTestUtils.getField(service, "queue")).drain();
|
||||
Map<String, Object> snapshot = metrics.snapshot();
|
||||
assertEquals(1L, snapshot.get("audit_write_failures_total"));
|
||||
assertEquals(0L, snapshot.get("audit_fallback_messages_total"));
|
||||
assertEquals(2L, snapshot.get("audit_lost_or_unconfirmed_messages_total"));
|
||||
assertFalse(service.recordAsync(Arrays.asList(delta(1, 0, 1, 0, 1))));
|
||||
assertEquals(3L, metrics.snapshot().get("degraded_messages_total"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulAuditCommitsAndRecordsSamplingMetrics() {
|
||||
BacklogRetentionAuditMapper mapper = mock(BacklogRetentionAuditMapper.class);
|
||||
when(mapper.upsert(any())).thenReturn(1);
|
||||
PlatformTransactionManager transactionManager = transactionManager();
|
||||
BacklogSamplingMetrics metrics = new BacklogSamplingMetrics();
|
||||
BacklogSamplingAuditService service = new BacklogSamplingAuditService(
|
||||
mapper, properties(), metrics, transactionManager);
|
||||
|
||||
assertTrue(service.recordAsync(Arrays.asList(
|
||||
delta(1, 0, 1, 0, 1))));
|
||||
|
||||
org.mockito.Mockito.verifyNoInteractions(mapper, transactionManager);
|
||||
((BestEffortAuxiliaryQueue) ReflectionTestUtils.getField(service, "queue")).drain();
|
||||
verify(mapper).upsert(any());
|
||||
verify(transactionManager).commit(any());
|
||||
assertEquals(1L, metrics.snapshot().get("degraded_messages_total"));
|
||||
assertEquals(1L, metrics.snapshot().get("normal_rows_dropped_total"));
|
||||
}
|
||||
|
||||
private BacklogSamplingProperties properties() {
|
||||
BacklogSamplingProperties properties = new BacklogSamplingProperties();
|
||||
ReflectionTestUtils.setField(properties, "auditTimeoutSeconds", 5);
|
||||
ReflectionTestUtils.setField(properties, "auditRetryBackoffMs", 60_000L);
|
||||
return properties;
|
||||
}
|
||||
|
||||
private PlatformTransactionManager transactionManager() {
|
||||
PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class);
|
||||
TransactionStatus status = mock(TransactionStatus.class);
|
||||
when(transactionManager.getTransaction(any(TransactionDefinition.class))).thenReturn(status);
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
private BacklogRetentionDelta delta(long messages, long normalSaved, long normalDropped,
|
||||
long rawSaved, long rawDropped) {
|
||||
return new BacklogRetentionDelta(LocalDateTime.of(2026, 9, 12, 18, 0),
|
||||
"raw", 0, "v1", 1000, 10000,
|
||||
messages, 0, 0, 1, normalSaved, normalDropped,
|
||||
0, 0, 0, 1, rawSaved, rawDropped, 3_600_000L, 3_600_000L);
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.common.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class BestEffortAuxiliaryQueueTest {
|
||||
@Test
|
||||
void hungAuxiliaryDatabaseDoesNotBlockMainEnqueueAndCapacityIsBounded() throws Exception {
|
||||
BestEffortAuxiliaryQueue queue = new BestEffortAuxiliaryQueue("TEST", 1, 2, true);
|
||||
CountDownLatch entered = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
assertTrue(queue.offer(1, () -> {
|
||||
entered.countDown();
|
||||
try { release.await(5, TimeUnit.SECONDS); }
|
||||
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
|
||||
}));
|
||||
CompletableFuture<Void> writer = CompletableFuture.runAsync(queue::drain);
|
||||
try {
|
||||
assertTrue(entered.await(2, TimeUnit.SECONDS));
|
||||
CompletableFuture.runAsync(() -> {
|
||||
assertTrue(queue.offer(1, () -> { }));
|
||||
assertFalse(queue.offer(1, () -> fail("overflow must never run")));
|
||||
}).get(2, TimeUnit.SECONDS);
|
||||
assertEquals(2L, queue.status().get("pending_groups"));
|
||||
assertEquals(1L, queue.status().get("lost_tasks_total"));
|
||||
} finally {
|
||||
release.countDown();
|
||||
writer.get(3, TimeUnit.SECONDS);
|
||||
queue.stop();
|
||||
}
|
||||
assertEquals(2L, queue.status().get("completed_total"));
|
||||
assertEquals(0L, queue.status().get("pending_groups"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditFailureIsNotAutomaticallyReplayedAndCapacityIsReleased() {
|
||||
BestEffortAuxiliaryQueue queue = new BestEffortAuxiliaryQueue("AUDIT_TEST", 1, 1, false);
|
||||
AtomicInteger attempts = new AtomicInteger();
|
||||
assertTrue(queue.offer(1, () -> { attempts.incrementAndGet(); throw new IllegalStateException("unknown commit"); }));
|
||||
assertDoesNotThrow(queue::drain);
|
||||
queue.drain();
|
||||
assertEquals(1, attempts.get());
|
||||
assertEquals(0L, queue.status().get("pending_groups"));
|
||||
assertTrue(queue.offer(1, () -> { }));
|
||||
queue.drain();
|
||||
assertEquals(1L, queue.status().get("completed_total"));
|
||||
queue.stop();
|
||||
assertFalse(queue.offer(1, () -> fail("closed")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void queueCountLimitAlsoReleasesReservedGroups() {
|
||||
BestEffortAuxiliaryQueue queue = new BestEffortAuxiliaryQueue("TEST", 1, 100, false);
|
||||
assertTrue(queue.offer(1, () -> { }));
|
||||
assertFalse(queue.offer(1, () -> fail("overflow")));
|
||||
assertEquals(1L, queue.status().get("pending_groups"));
|
||||
queue.drain();
|
||||
assertEquals(0L, queue.status().get("pending_groups"));
|
||||
}
|
||||
}
|
||||
+14
-21
@@ -36,7 +36,7 @@ class DirectStatsProjectionWriterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void directModeWritesOnlyDimensionBatchesAndMaterializesAffectedRows() {
|
||||
void directModeAggregatesWithoutAnyStatisticsSql() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
DirectStatsProjectionWriter writer = writer(jdbc, "DIRECT", true);
|
||||
TransactionSynchronizationManager.setActualTransactionActive(true);
|
||||
@@ -53,13 +53,7 @@ class DirectStatsProjectionWriterTest {
|
||||
|
||||
writer.writeStandardizedRows(rows);
|
||||
|
||||
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
|
||||
verify(jdbc, times(4)).batchUpdate(sql.capture(), anyList());
|
||||
String combined = String.join("\n", sql.getAllValues());
|
||||
assertTrue(combined.contains("MERGE INTO device_daily_stats"));
|
||||
assertTrue(combined.contains("MERGE INTO normalize_rule_daily_stats"));
|
||||
assertTrue(combined.contains("UPDATE device_device"));
|
||||
assertTrue(combined.contains("UPDATE dm_normalize_rule"));
|
||||
verifyNoInteractions(jdbc);
|
||||
assertTrue(((Number) writer.status().get("input_rows")).longValue() == 100L);
|
||||
assertTrue(((Number) writer.status().get("device_groups")).longValue() == 1L);
|
||||
assertTrue(((Number) writer.status().get("rule_groups")).longValue() == 2L);
|
||||
@@ -76,7 +70,7 @@ class DirectStatsProjectionWriterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonNormalUpdateRecomputesOnlyAffectedFactGroupsExactly() {
|
||||
void shadowNonNormalUpdateRetainsExactRecomputation() {
|
||||
AtomicInteger exactQueries = new AtomicInteger();
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class, invocation -> {
|
||||
if ("queryForMap".equals(invocation.getMethod().getName())) {
|
||||
@@ -88,7 +82,7 @@ class DirectStatsProjectionWriterTest {
|
||||
}
|
||||
return Answers.RETURNS_DEFAULTS.answer(invocation);
|
||||
});
|
||||
DirectStatsProjectionWriter writer = writer(jdbc, "DIRECT", true);
|
||||
DirectStatsProjectionWriter writer = writer(jdbc, "DIRECT_SHADOW", true);
|
||||
TransactionSynchronizationManager.setActualTransactionActive(true);
|
||||
LocalDate today = LocalDate.now(ZoneId.of("Asia/Shanghai"));
|
||||
com.common.entity.SyslogNonNormalMessage oldValue =
|
||||
@@ -104,9 +98,8 @@ class DirectStatsProjectionWriterTest {
|
||||
|
||||
assertTrue(exactQueries.get() == 2);
|
||||
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
|
||||
verify(jdbc, times(2)).batchUpdate(sql.capture(), anyList());
|
||||
verify(jdbc).batchUpdate(sql.capture(), anyList());
|
||||
assertTrue(sql.getAllValues().get(0).contains("parse_count=s.parse_count"));
|
||||
assertTrue(sql.getAllValues().get(1).contains("UPDATE device_device"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -119,12 +112,13 @@ class DirectStatsProjectionWriterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void kafkaMaterializationRemovesBusinessTableUpdatesFromFactTransaction() {
|
||||
void afterCommitPublisherRemovesAllStatisticsSqlFromFactTransaction() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
StatsMaterializationPublisher publisher = mock(StatsMaterializationPublisher.class);
|
||||
when(publisher.isEnabled()).thenReturn(true);
|
||||
StatsProjectionAsyncPublisher outbox = mock(StatsProjectionAsyncPublisher.class);
|
||||
DirectStatsProjectionWriter writer = new DirectStatsProjectionWriter(
|
||||
jdbc, new StatsWriteModeProvider("DIRECT"), new DirectStatsWriteMetrics(), publisher);
|
||||
jdbc, new StatsWriteModeProvider("DIRECT"), new DirectStatsWriteMetrics(), publisher, outbox);
|
||||
configure(writer, true);
|
||||
TransactionSynchronizationManager.setActualTransactionActive(true);
|
||||
|
||||
@@ -135,20 +129,19 @@ class DirectStatsProjectionWriterTest {
|
||||
row.put("normalize_rule_id", 11L);
|
||||
writer.writeStandardizedRow(row);
|
||||
|
||||
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
|
||||
verify(jdbc, times(2)).batchUpdate(sql.capture(), anyList());
|
||||
assertTrue(sql.getAllValues().get(0).contains("MERGE INTO device_daily_stats"));
|
||||
assertTrue(sql.getAllValues().get(1).contains("MERGE INTO normalize_rule_daily_stats"));
|
||||
verify(publisher).enqueueAfterCommit(anyCollection());
|
||||
assertTrue("KAFKA_DIRTY_KEY".equals(writer.status().get("business_materialization_mode")));
|
||||
verify(outbox).enqueueAfterCommit(org.mockito.ArgumentMatchers.any(StatsProjectionOutboxEvent.class),
|
||||
org.mockito.ArgumentMatchers.eq(1));
|
||||
verifyNoInteractions(jdbc);
|
||||
assertTrue("BEST_EFFORT_AFTER_COMMIT_KAFKA".equals(writer.status().get("daily_projection_write_mode")));
|
||||
}
|
||||
|
||||
private DirectStatsProjectionWriter writer(JdbcTemplate jdbc, String mode, boolean readEnabled) {
|
||||
StatsWriteModeProvider modeProvider = new StatsWriteModeProvider(mode);
|
||||
StatsMaterializationPublisher publisher = mock(StatsMaterializationPublisher.class);
|
||||
when(publisher.isEnabled()).thenReturn(false);
|
||||
StatsProjectionAsyncPublisher outbox = mock(StatsProjectionAsyncPublisher.class);
|
||||
DirectStatsProjectionWriter writer = new DirectStatsProjectionWriter(
|
||||
jdbc, modeProvider, new DirectStatsWriteMetrics(), publisher);
|
||||
jdbc, modeProvider, new DirectStatsWriteMetrics(), publisher, outbox);
|
||||
configure(writer, readEnabled);
|
||||
return writer;
|
||||
}
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class DmLargeTextLimiterTest {
|
||||
|
||||
@Test
|
||||
void normalConfiguredFieldsAreTruncatedButOtherFieldsRemainUntouched() {
|
||||
DmLargeTextLimiter limiter = limiter(96L, "http_req_body,description", 0L);
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
row.put("http_req_body", repeat("中文🙂", 100));
|
||||
row.put("other", repeat("x", 200));
|
||||
|
||||
limiter.truncateNormalRow(row);
|
||||
|
||||
String body = (String) row.get("http_req_body");
|
||||
assertTrue(body.contains("HB_XDR_TRUNCATED"));
|
||||
assertTrue(body.getBytes(StandardCharsets.UTF_8).length <= 96);
|
||||
assertEquals(repeat("x", 200), row.get("other"));
|
||||
assertEquals(1L, limiter.getNormalFieldsTruncated());
|
||||
}
|
||||
|
||||
@Test
|
||||
void allNonNormalLargeColumnsUseTheSameVisibleMarker() {
|
||||
DmLargeTextLimiter limiter = limiter(0L, "", 96L);
|
||||
SyslogNonNormalMessage message = new SyslogNonNormalMessage();
|
||||
message.setSyslogMessage(repeat("原文", 100));
|
||||
message.setHeaderMessage(repeat("头", 100));
|
||||
message.setReasonDetail(repeat("原因", 100));
|
||||
|
||||
limiter.truncateNonNormal(message);
|
||||
|
||||
assertTrue(message.getSyslogMessage().contains("HB_XDR_TRUNCATED"));
|
||||
assertTrue(message.getHeaderMessage().contains("HB_XDR_TRUNCATED"));
|
||||
assertTrue(message.getReasonDetail().contains("HB_XDR_TRUNCATED"));
|
||||
assertEquals(3L, limiter.getNonNormalFieldsTruncated());
|
||||
}
|
||||
|
||||
private DmLargeTextLimiter limiter(long normal, String fields, long nonNormal) {
|
||||
DmLargeTextLimiter limiter = new DmLargeTextLimiter();
|
||||
ReflectionTestUtils.setField(limiter, "normalMaxBytes", normal);
|
||||
ReflectionTestUtils.setField(limiter, "normalFieldsValue", fields);
|
||||
ReflectionTestUtils.setField(limiter, "nonNormalMaxBytes", nonNormal);
|
||||
limiter.validate();
|
||||
return limiter;
|
||||
}
|
||||
|
||||
private static String repeat(String value, int count) {
|
||||
StringBuilder result = new StringBuilder(value.length() * count);
|
||||
for (int i = 0; i < count; i++) result.append(value);
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
package com.common.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.Types;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class DmPreparedBatchInserterTest {
|
||||
|
||||
@Test
|
||||
void buildsOneCanonicalInsertFromBatchUnionAndDatabaseWhitelist() {
|
||||
Map<String, Integer> columns = new LinkedHashMap<>();
|
||||
columns.put("id", Types.VARCHAR);
|
||||
columns.put("created_at", Types.TIMESTAMP);
|
||||
columns.put("src_ip", Types.VARCHAR);
|
||||
columns.put("dest_ip", Types.VARCHAR);
|
||||
|
||||
Map<String, Object> first = new LinkedHashMap<>();
|
||||
first.put("src_ip", "10.0.0.1");
|
||||
first.put("id", "row-1");
|
||||
first.put("unknown_rule_field", "ignored");
|
||||
Map<String, Object> second = new LinkedHashMap<>();
|
||||
second.put("id", "row-2");
|
||||
second.put("dest_ip", "10.0.0.2");
|
||||
second.put("src_ip", null);
|
||||
|
||||
DmPreparedBatchInserter.BatchPlan plan = DmPreparedBatchInserter.buildPlan(
|
||||
DmPreparedBatchInserter.NORMAL_TABLE, Arrays.asList(first, second),
|
||||
DmPreparedBatchInserter.TableMetadata.of(columns));
|
||||
|
||||
assertEquals("INSERT INTO syslog_normal_data (id,src_ip,dest_ip) VALUES (?,?,?)", plan.sql);
|
||||
assertEquals(3, plan.columns.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void bindsDatesAndUsesDatabaseTypeForMissingValues() throws Exception {
|
||||
PreparedStatement statement = mock(PreparedStatement.class);
|
||||
LocalDateTime createdAt = LocalDateTime.of(2026, 9, 13, 2, 30);
|
||||
Date logTime = new Date(1_700_000_000_000L);
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("id", "row-1");
|
||||
row.put("created_at", createdAt);
|
||||
row.put("log_time", logTime);
|
||||
|
||||
List<DmPreparedBatchInserter.ColumnMetadata> columns = Arrays.asList(
|
||||
new DmPreparedBatchInserter.ColumnMetadata("id", Types.VARCHAR),
|
||||
new DmPreparedBatchInserter.ColumnMetadata("created_at", Types.TIMESTAMP),
|
||||
new DmPreparedBatchInserter.ColumnMetadata("log_time", Types.TIMESTAMP),
|
||||
new DmPreparedBatchInserter.ColumnMetadata("dest_ip", Types.VARCHAR));
|
||||
|
||||
DmPreparedBatchInserter.bindRow(statement, row, columns);
|
||||
|
||||
verify(statement).setObject(1, "row-1");
|
||||
verify(statement).setTimestamp(2, java.sql.Timestamp.valueOf(createdAt));
|
||||
verify(statement).setTimestamp(3, new java.sql.Timestamp(logTime.getTime()));
|
||||
verify(statement).setNull(4, Types.VARCHAR);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsDynamicTableNames() {
|
||||
Map<String, Integer> columns = new LinkedHashMap<>();
|
||||
columns.put("id", Types.VARCHAR);
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("id", "row-1");
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> DmPreparedBatchInserter.buildPlan(
|
||||
"syslog_normal_data;drop table x", Arrays.asList(row),
|
||||
DmPreparedBatchInserter.TableMetadata.of(columns)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preparesOneStatementAndExecutesOneJdbcBatchForAllRows() throws Exception {
|
||||
Connection connection = mock(Connection.class);
|
||||
PreparedStatement metadataStatement = mock(PreparedStatement.class);
|
||||
ResultSet metadataResult = mock(ResultSet.class);
|
||||
ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class);
|
||||
PreparedStatement insertStatement = mock(PreparedStatement.class);
|
||||
when(connection.prepareStatement("SELECT * FROM syslog_normal_data WHERE 1=0"))
|
||||
.thenReturn(metadataStatement);
|
||||
when(metadataStatement.executeQuery()).thenReturn(metadataResult);
|
||||
when(metadataResult.getMetaData()).thenReturn(resultSetMetaData);
|
||||
when(resultSetMetaData.getColumnCount()).thenReturn(2);
|
||||
when(resultSetMetaData.getColumnName(1)).thenReturn("ID");
|
||||
when(resultSetMetaData.getColumnName(2)).thenReturn("SRC_IP");
|
||||
when(resultSetMetaData.getColumnType(1)).thenReturn(Types.VARCHAR);
|
||||
when(resultSetMetaData.getColumnType(2)).thenReturn(Types.VARCHAR);
|
||||
when(connection.prepareStatement(
|
||||
"INSERT INTO syslog_normal_data (id,src_ip) VALUES (?,?)"))
|
||||
.thenReturn(insertStatement);
|
||||
when(insertStatement.executeBatch()).thenReturn(new int[]{1, 1});
|
||||
|
||||
Map<String, Object> first = new LinkedHashMap<>();
|
||||
first.put("id", "row-1");
|
||||
first.put("src_ip", "10.0.0.1");
|
||||
Map<String, Object> second = new LinkedHashMap<>();
|
||||
second.put("id", "row-2");
|
||||
|
||||
DmPreparedBatchInserter inserter = new DmPreparedBatchInserter(mock(
|
||||
org.springframework.jdbc.core.JdbcTemplate.class));
|
||||
DmWriteSizeEstimate size = new DmWriteSizeEstimate();
|
||||
DmPreparedBatchInserter.BatchExecution result = inserter.execute(connection,
|
||||
DmPreparedBatchInserter.NORMAL_TABLE, Arrays.asList(first, second), 45, size);
|
||||
|
||||
assertEquals(2, result.getRows());
|
||||
assertEquals(2, result.getColumns());
|
||||
assertEquals(18L, size.getPayloadBytes());
|
||||
assertEquals(13L, size.getMaxRowBytes());
|
||||
assertEquals("src_ip", size.getMaxFieldName());
|
||||
verify(insertStatement, times(2)).addBatch();
|
||||
verify(insertStatement).executeBatch();
|
||||
verify(insertStatement).setNull(2, Types.VARCHAR);
|
||||
|
||||
when(insertStatement.executeBatch()).thenThrow(new java.sql.SQLException("test failure"));
|
||||
DmWriteSizeEstimate failedSize = new DmWriteSizeEstimate();
|
||||
assertThrows(java.sql.SQLException.class, () -> inserter.execute(connection,
|
||||
DmPreparedBatchInserter.NORMAL_TABLE, Arrays.asList(first, second), 45, failedSize));
|
||||
assertEquals("COMPLETE", failedSize.getStatus());
|
||||
assertEquals(18L, failedSize.getPayloadBytes());
|
||||
}
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package com.common.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
class DmStandardizedBatchExecutorTest {
|
||||
|
||||
@Test
|
||||
void alignsEveryRowToTheNonNullColumnUnionWithoutMutatingSources() {
|
||||
Map<String, Object> first = new HashMap<>();
|
||||
first.put("id", "row-1");
|
||||
first.put("src_ip", "10.0.0.1");
|
||||
first.put("unused_null", null);
|
||||
|
||||
Map<String, Object> second = new HashMap<>();
|
||||
second.put("id", "row-2");
|
||||
second.put("dest_ip", "10.0.0.2");
|
||||
|
||||
List<Map<String, Object>> aligned =
|
||||
DmStandardizedBatchExecutor.alignBatchColumns(Arrays.asList(first, second));
|
||||
|
||||
assertEquals(aligned.get(0).keySet(), aligned.get(1).keySet());
|
||||
assertEquals(Arrays.asList("dest_ip", "id", "src_ip"),
|
||||
aligned.get(0).keySet().stream().sorted().collect(java.util.stream.Collectors.toList()));
|
||||
assertEquals("10.0.0.1", aligned.get(0).get("src_ip"));
|
||||
assertNull(aligned.get(0).get("dest_ip"));
|
||||
assertNull(aligned.get(1).get("src_ip"));
|
||||
assertEquals("10.0.0.2", aligned.get(1).get("dest_ip"));
|
||||
assertFalse(aligned.get(0).containsKey("unused_null"));
|
||||
assertFalse(first.containsKey("dest_ip"), "不得修改上游标准化结果 Map");
|
||||
assertFalse(second.containsKey("src_ip"), "不得修改上游标准化结果 Map");
|
||||
}
|
||||
}
|
||||
+47
@@ -54,6 +54,53 @@ class DmStandardizedBatchWriterTest {
|
||||
when(normalDataService.isAlarmData(any())).thenReturn(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalAndAlarmBatchesUse2000LimitAndWriteTailImmediately() {
|
||||
ReflectionTestUtils.setField(writer, "batchSize", 2000);
|
||||
List<Integer> sizes = new ArrayList<>();
|
||||
doAnswer(invocation -> {
|
||||
sizes.add(((List<?>) invocation.getArgument(1)).size());
|
||||
return null;
|
||||
}).when(batchExecutor).execute(anyBoolean(), anyList(), anyInt());
|
||||
for (boolean alarm : new boolean[]{false, true}) {
|
||||
when(normalDataService.isAlarmData(any())).thenReturn(alarm);
|
||||
sizes.clear();
|
||||
assertEquals(3000, writer.write(requests(3000, -1)).getSuccessfulRows());
|
||||
assertEquals(java.util.Arrays.asList(2000, 1000), sizes);
|
||||
sizes.clear();
|
||||
assertEquals(500, writer.write(requests(500, -1)).getSuccessfulRows());
|
||||
assertEquals(java.util.Collections.singletonList(500), sizes);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void alarmsKeepLegacyTruncationInBothBatchAndSingleMode() {
|
||||
DmLargeTextLimiter limiter = new DmLargeTextLimiter();
|
||||
ReflectionTestUtils.setField(limiter, "normalMaxBytes", 64L);
|
||||
ReflectionTestUtils.setField(limiter, "normalFieldsValue", "description");
|
||||
limiter.validate();
|
||||
ReflectionTestUtils.setField(writer, "largeTextLimiter", limiter);
|
||||
when(normalDataService.isAlarmData(any())).thenAnswer(invocation ->
|
||||
((Map<?, ?>) invocation.getArgument(0)).get("event_level") != null);
|
||||
when(normalDataService.insertDynamic(any())).thenReturn(1);
|
||||
String content = String.join("", java.util.Collections.nCopies(300000, "x"));
|
||||
for (String mode : java.util.Arrays.asList("BATCH", "SINGLE")) {
|
||||
ReflectionTestUtils.setField(writer, "mode", mode);
|
||||
List<DmStandardizedBatchWriter.WriteRequest<String>> requests = requests(2, -1);
|
||||
requests.get(0).getData().put("event_level", "HIGH");
|
||||
requests.get(0).getData().put("description", content);
|
||||
requests.get(1).getData().put("description", content);
|
||||
DmStandardizedBatchWriter.WriteReport<String> report = writer.write(requests);
|
||||
assertEquals(2, report.getSuccessfulRows());
|
||||
String alarm = (String) requests.get(0).getData().get("description");
|
||||
assertTrue(alarm.contains("HB_XDR_TRUNCATED"), "告警仍遵守旧的大字段上限");
|
||||
assertTrue(alarm.getBytes(java.nio.charset.StandardCharsets.UTF_8).length <= 64);
|
||||
String ordinary = (String) requests.get(1).getData().get("description");
|
||||
assertTrue(ordinary.contains("HB_XDR_TRUNCATED"));
|
||||
assertTrue(ordinary.getBytes(java.nio.charset.StandardCharsets.UTF_8).length <= 64);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void oneBadRowIsIsolatedWithoutDowngradingEveryGoodRowToSingleInsert() {
|
||||
List<DmStandardizedBatchWriter.WriteRequest<String>> requests = requests(100, 73);
|
||||
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package com.common.service;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import org.apache.ibatis.session.Configuration;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
|
||||
import org.springframework.transaction.support.DefaultTransactionStatus;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class DmTransactionWriteSizeLogTest {
|
||||
@Test
|
||||
void successfulSlowNormalAndAlarmTransactionsIncludeOnlySizeMetadata() {
|
||||
check(false, false);
|
||||
check(true, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedWriteIncludesAttemptedPayloadAndStillThrows() {
|
||||
check(false, true);
|
||||
}
|
||||
|
||||
private void check(boolean alarm, boolean fail) {
|
||||
SqlSessionFactory sessions = mock(SqlSessionFactory.class);
|
||||
Configuration configuration = new Configuration();
|
||||
configuration.setEnvironment(new org.apache.ibatis.mapping.Environment("test",
|
||||
new org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory(), mock(javax.sql.DataSource.class)));
|
||||
when(sessions.getConfiguration()).thenReturn(configuration);
|
||||
DmPreparedBatchInserter inserter = mock(DmPreparedBatchInserter.class);
|
||||
when(inserter.insert(eq(alarm), anyList(), anyInt(), any(DmWriteSizeEstimate.class)))
|
||||
.thenAnswer(invocation -> {
|
||||
DmWriteSizeEstimate size = invocation.getArgument(3);
|
||||
size.measure(invocation.getArgument(1), DmWriteSizeEstimateTest.columns("detail"));
|
||||
if (fail) throw new IllegalStateException("write failed");
|
||||
return new DmPreparedBatchInserter.BatchExecution(1, 1, 0, 0, 0);
|
||||
});
|
||||
AbstractPlatformTransactionManager transactions = new AbstractPlatformTransactionManager() {
|
||||
protected Object doGetTransaction() { return new Object(); }
|
||||
protected void doBegin(Object transaction, TransactionDefinition definition) { }
|
||||
protected void doCommit(DefaultTransactionStatus status) {
|
||||
// 使成功事务确定超过1ms阈值,不依赖真实数据库。
|
||||
java.util.concurrent.locks.LockSupport.parkNanos(5_000_000L);
|
||||
}
|
||||
protected void doRollback(DefaultTransactionStatus status) { }
|
||||
};
|
||||
DmStandardizedBatchExecutor executor = new DmStandardizedBatchExecutor(sessions, transactions,
|
||||
inserter, mock(StatsChangeCaptureService.class), mock(DirectStatsProjectionWriter.class),
|
||||
new DmDirectTransactionMetrics(), mock(LateAlarmBucketWriter.class));
|
||||
ReflectionTestUtils.setField(executor, "slowTransactionThresholdMs", 1L);
|
||||
Logger logger = (Logger) LoggerFactory.getLogger(DmStandardizedBatchExecutor.class);
|
||||
ListAppender<ILoggingEvent> appender = new ListAppender<>();
|
||||
appender.start();
|
||||
logger.addAppender(appender);
|
||||
List<Map<String, Object>> rows = Collections.singletonList(
|
||||
Collections.<String, Object>singletonMap("detail", "秘密😀"));
|
||||
try {
|
||||
if (fail) assertThrows(IllegalStateException.class, () -> executor.execute(alarm, rows, 45));
|
||||
else executor.execute(alarm, rows, 45);
|
||||
String message = appender.list.stream().map(ILoggingEvent::getFormattedMessage)
|
||||
.filter(text -> text.contains("[SLOW_DM_TRANSACTION]")).findFirst().orElse("");
|
||||
assertTrue(message.contains("table=" + (alarm ? "syslog_normal_alarm" : "syslog_normal_data")));
|
||||
assertTrue(message.contains("status=" + (fail ? "FAILED" : "SUCCESS")));
|
||||
assertTrue(message.contains("sizeEstimateStatus=COMPLETE"));
|
||||
assertTrue(message.contains("estimatedPayloadBytes=10"));
|
||||
assertTrue(message.contains("maxRowEstimatedBytes=10"));
|
||||
assertTrue(message.contains("maxFieldEstimatedBytes=10"));
|
||||
assertTrue(message.contains("maxFieldName=detail"));
|
||||
assertTrue(message.contains("sizeEstimateMs="));
|
||||
assertFalse(message.contains("秘密"));
|
||||
} finally {
|
||||
logger.detachAppender(appender);
|
||||
appender.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package com.common.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Types;
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class DmWriteSizeEstimateTest {
|
||||
@Test
|
||||
void utf8MatchesJdkForAsciiChineseEmojiMalformedSurrogatesAndRandomText() {
|
||||
for (String text : Arrays.asList("", "ascii", "中文😀", "\uD800", "\uDC00", "\uD800x\uDC00")) {
|
||||
assertEquals(text.getBytes(StandardCharsets.UTF_8).length, DmWriteSizeEstimate.utf8Length(text));
|
||||
}
|
||||
Random random = new Random(42);
|
||||
for (int i = 0; i < 200; i++) {
|
||||
char[] chars = new char[1024];
|
||||
for (int j = 0; j < chars.length; j++) chars[j] = (char) random.nextInt(65536);
|
||||
String text = new String(chars);
|
||||
assertEquals(text.getBytes(StandardCharsets.UTF_8).length, DmWriteSizeEstimate.utf8Length(text));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void measuresOnlyBoundColumnsAndDoesNotMutateRowsOrLogValues() {
|
||||
Map<String, Object> first = new LinkedHashMap<>();
|
||||
first.put("id", "a");
|
||||
first.put("detail", "敏感内容😀"); // 16 UTF-8 bytes
|
||||
first.put("ignored", "not-in-sql");
|
||||
Map<String, Object> second = new LinkedHashMap<>();
|
||||
second.put("id", "bc");
|
||||
second.put("detail", new byte[3]);
|
||||
Map<String, Object> snapshot = new LinkedHashMap<>(first);
|
||||
DmWriteSizeEstimate size = new DmWriteSizeEstimate();
|
||||
size.measure(Arrays.asList(first, second), columns("id", "detail"));
|
||||
assertEquals(22L, size.getPayloadBytes());
|
||||
assertEquals(17L, size.getMaxRowBytes());
|
||||
assertEquals(16L, size.getMaxFieldBytes());
|
||||
assertEquals("detail", size.getMaxFieldName());
|
||||
assertEquals("COMPLETE", size.getStatus());
|
||||
assertEquals(snapshot, first);
|
||||
assertFalse(size.toString().contains("敏感内容"));
|
||||
assertFalse(size.toString().contains("not-in-sql"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void measuresTruncatedValuesNotOriginalAndKeepsTruncationMarker() {
|
||||
DmLargeTextLimiter limiter = new DmLargeTextLimiter();
|
||||
ReflectionTestUtils.setField(limiter, "normalMaxBytes", 64L);
|
||||
ReflectionTestUtils.setField(limiter, "normalFieldsValue", "detail");
|
||||
limiter.validate();
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("detail", String.join("", Collections.nCopies(100, "中")));
|
||||
limiter.truncateNormalRow(row);
|
||||
String truncated = (String) row.get("detail");
|
||||
assertTrue(truncated.getBytes(StandardCharsets.UTF_8).length <= 64);
|
||||
DmWriteSizeEstimate size = new DmWriteSizeEstimate();
|
||||
size.measure(Collections.singletonList(row), columns("detail"));
|
||||
assertEquals(truncated.getBytes(StandardCharsets.UTF_8).length, size.getPayloadBytes());
|
||||
assertSame(truncated, row.get("detail"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlesNullScalarsAndUnknownWithoutCallingArbitraryToString() {
|
||||
Object unknown = new Object() {
|
||||
@Override public String toString() { throw new AssertionError("must not stringify"); }
|
||||
};
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("id", 123);
|
||||
row.put("flag", true);
|
||||
row.put("unknown", unknown);
|
||||
row.put("missing", null);
|
||||
DmWriteSizeEstimate size = new DmWriteSizeEstimate();
|
||||
size.measure(Collections.singletonList(row), columns("id", "flag", "unknown", "missing"));
|
||||
assertEquals(7L, size.getPayloadBytes());
|
||||
assertEquals(1L, size.getUnmeasuredValues());
|
||||
assertEquals("PARTIAL", size.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void diagnosticFailureIsMarkedWithoutThrowingAndUnmeasuredIsExplicit() {
|
||||
DmWriteSizeEstimate size = new DmWriteSizeEstimate();
|
||||
assertEquals("NOT_MEASURED", size.getStatus());
|
||||
Map<String, Object> bad = new HashMap<String, Object>() {
|
||||
@Override public Object get(Object key) { throw new IllegalStateException("sensitive value"); }
|
||||
};
|
||||
assertDoesNotThrow(() -> size.measure(Collections.singletonList(bad), columns("id")));
|
||||
assertEquals("FAILED", size.getStatus());
|
||||
assertFalse(size.toString().contains("sensitive value"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void totalUsesLongBeyondTwoGiBWithoutAllocatingAnEncodedCopy() {
|
||||
String text = String.join("", Collections.nCopies(1024 * 1024, "a"));
|
||||
DmWriteSizeEstimate size = new DmWriteSizeEstimate();
|
||||
size.measure(Collections.nCopies(2050, Collections.<String, Object>singletonMap("detail", text)),
|
||||
columns("detail"));
|
||||
assertEquals(2050L * 1024 * 1024, size.getPayloadBytes());
|
||||
}
|
||||
|
||||
static List<DmPreparedBatchInserter.ColumnMetadata> columns(String... names) {
|
||||
List<DmPreparedBatchInserter.ColumnMetadata> columns = new ArrayList<>();
|
||||
for (String name : names) columns.add(new DmPreparedBatchInserter.ColumnMetadata(name, Types.VARCHAR));
|
||||
return columns;
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.Modules.NormalData.SyslogFailureRouter;
|
||||
import com.common.entity.IngressStatsEvent;
|
||||
import com.common.util.Sm4Util;
|
||||
import com.config.AppProperties;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
import org.springframework.kafka.core.KafkaTemplate;
|
||||
import org.springframework.kafka.support.Acknowledgment;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
|
||||
class IngressStatsConsumerTest {
|
||||
private static final String KEY = "0123456789abcdeffedcba9876543210";
|
||||
private final IngressStatsProjectionWriter writer = mock(IngressStatsProjectionWriter.class);
|
||||
private final Acknowledgment ack = mock(Acknowledgment.class);
|
||||
|
||||
private IngressStatsConsumer consumer() {
|
||||
AppProperties properties = mock(AppProperties.class);
|
||||
when(properties.getSm4Key()).thenReturn(KEY);
|
||||
return new IngressStatsConsumer(writer,
|
||||
new SyslogFailureRouter(mock(KafkaTemplate.class), new ObjectMapper()), properties);
|
||||
}
|
||||
|
||||
private ConsumerRecord<String, String> record(String topic, long offset, String time) {
|
||||
String value = Sm4Util.encryptCbc("[device_id=126 device_collect_id=3 receive_time="
|
||||
+ time + " event_time=20000101000000000]正文不参与规则或时间统计", KEY);
|
||||
return new ConsumerRecord<>(topic, 0, offset, "key", value);
|
||||
}
|
||||
|
||||
@Test
|
||||
void decodesActualEncryptedHeaderUsingReceiveTimeNotEventTime() {
|
||||
IngressStatsEvent event = consumer().decode(record("raw", 0, "20260913044500000"));
|
||||
assertEquals(Long.valueOf(126), event.getDeviceId());
|
||||
assertEquals(Long.valueOf(3), event.getDeviceCollectId());
|
||||
assertEquals(LocalDateTime.of(2026, 9, 13, 4, 45), event.getReceiveTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
void commitsOnlyAfterStatsDatabaseReturnsAndSupportsLargeTopic() {
|
||||
consumer().consumeLarge(Collections.singletonList(record("raw.large", 1, "20260913044500000")), ack);
|
||||
InOrder order = inOrder(writer, ack);
|
||||
order.verify(writer).writeBatch(anyList());
|
||||
order.verify(ack).acknowledge();
|
||||
}
|
||||
|
||||
@Test
|
||||
void databaseFailureRetainsStatsOffsetForRetry() {
|
||||
when(writer.writeBatch(anyList())).thenThrow(new IllegalStateException("database down"));
|
||||
assertThrows(IllegalStateException.class, () -> consumer().consume(
|
||||
Collections.singletonList(record("raw", 0, "20260913044500000")), ack));
|
||||
verifyNoInteractions(ack);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidHeaderIsCountedWithoutDiscardingOtherRecords() {
|
||||
IngressStatsConsumer consumer = consumer();
|
||||
consumer.consume(Arrays.asList(new ConsumerRecord<>("raw", 0, 0L, "k", "bad ciphertext"),
|
||||
record("raw", 1L, "20260913044500000")), ack);
|
||||
ArgumentCaptor<List<IngressStatsEvent>> events = ArgumentCaptor.forClass(List.class);
|
||||
verify(writer).writeBatch(events.capture());
|
||||
assertEquals(1, events.getValue().size());
|
||||
assertEquals(1L, consumer.status().get("invalid_record_attempts"));
|
||||
verify(ack).acknowledge();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsSharingBusinessConsumerGroup() {
|
||||
IngressStatsConsumer consumer = consumer();
|
||||
ReflectionTestUtils.setField(consumer, "rawGroup", "business");
|
||||
ReflectionTestUtils.setField(consumer, "largeRawGroup", "business-large");
|
||||
ReflectionTestUtils.setField(consumer, "group", "business");
|
||||
ReflectionTestUtils.setField(consumer, "largeGroup", "stats-large");
|
||||
assertThrows(IllegalStateException.class, consumer::validateGroups);
|
||||
ReflectionTestUtils.setField(consumer, "group", "stats");
|
||||
assertDoesNotThrow(consumer::validateGroups);
|
||||
}
|
||||
}
|
||||
+35
@@ -2,6 +2,11 @@ package com.common.service;
|
||||
|
||||
import com.common.entity.IngressStatsEvent;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.SimpleTransactionStatus;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
@@ -9,6 +14,11 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class IngressStatsProjectionWriterTest {
|
||||
@Test
|
||||
@@ -41,4 +51,29 @@ class IngressStatsProjectionWriterTest {
|
||||
assertEquals(Arrays.asList(8L, 2L, 9L), devices);
|
||||
assertEquals(Arrays.asList(3L, 4L, 7L), new ArrayList<>(result.collects.keySet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void independentIngressWritesAggregatedMinMaxDirectlyAndCommits() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
PlatformTransactionManager manager = mock(PlatformTransactionManager.class);
|
||||
when(manager.getTransaction(any(TransactionDefinition.class)))
|
||||
.thenReturn(new SimpleTransactionStatus());
|
||||
IngressStatsProjectionWriter writer = new IngressStatsProjectionWriter(
|
||||
jdbc, manager, new StatsWriteModeProvider("DIRECT"),
|
||||
mock(StatsMaterializationPublisher.class));
|
||||
ReflectionTestUtils.setField(writer, "enabled", true);
|
||||
ReflectionTestUtils.setField(writer, "transactionTimeoutSeconds", 45);
|
||||
ReflectionTestUtils.setField(writer, "businessZone", "Asia/Shanghai");
|
||||
|
||||
int groups = writer.writeBatch(Arrays.asList(
|
||||
new IngressStatsEvent("a", 7L, 3L, LocalDateTime.of(2026, 9, 12, 8, 0)),
|
||||
new IngressStatsEvent("b", 7L, 3L, LocalDateTime.of(2026, 9, 12, 8, 1))));
|
||||
|
||||
assertEquals(2, groups);
|
||||
verify(jdbc).update(org.mockito.ArgumentMatchers.contains("MERGE INTO device_daily_stats"),
|
||||
any(), any(), any());
|
||||
verify(jdbc).update(org.mockito.ArgumentMatchers.contains("MERGE INTO device_collect_stats"),
|
||||
any(), any(), any());
|
||||
verify(manager).commit(any());
|
||||
}
|
||||
}
|
||||
|
||||
+77
-5
@@ -6,6 +6,8 @@ import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
@@ -16,14 +18,60 @@ import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
class LateAlarmBucketWriterTest {
|
||||
private final org.springframework.transaction.support.TransactionTemplate transaction =
|
||||
new org.springframework.transaction.support.TransactionTemplate(new TestTransactionManager());
|
||||
|
||||
@org.junit.jupiter.api.AfterEach void clean() {
|
||||
org.springframework.transaction.support.TransactionSynchronizationManager.clear();
|
||||
}
|
||||
|
||||
private LateAlarmBucketWriter writer(JdbcTemplate jdbc) {
|
||||
LateAlarmBucketWriter writer = new LateAlarmBucketWriter(jdbc, new TestTransactionManager());
|
||||
ReflectionTestUtils.setField(writer, "enabled", true);
|
||||
return writer;
|
||||
}
|
||||
|
||||
private void committed(LateAlarmBucketWriter writer, java.util.List<Map<String, Object>> rows) {
|
||||
transaction.execute(status -> { writer.record(rows); return null; });
|
||||
((BestEffortAuxiliaryQueue) ReflectionTestUtils.getField(writer, "queue")).drain();
|
||||
}
|
||||
|
||||
private static class TestTransactionManager extends org.springframework.transaction.support.AbstractPlatformTransactionManager {
|
||||
protected Object doGetTransaction() { return new Object(); }
|
||||
protected void doBegin(Object tx, org.springframework.transaction.TransactionDefinition def) { }
|
||||
protected void doCommit(org.springframework.transaction.support.DefaultTransactionStatus status) { }
|
||||
protected void doRollback(org.springframework.transaction.support.DefaultTransactionStatus status) { }
|
||||
}
|
||||
|
||||
@Test
|
||||
void takesBucketLocksInSameOrderForReversedBatches() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
LateAlarmBucketWriter writer = writer(jdbc);
|
||||
ReflectionTestUtils.setField(writer, "enabled", true);
|
||||
java.util.List<String> locks = new java.util.ArrayList<>();
|
||||
doAnswer(call -> {
|
||||
locks.add(call.getArgument(1) + ":" + call.getArgument(2));
|
||||
return 1;
|
||||
}).when(jdbc).update(anyString(), any(), any(), any(), any(), any(), any());
|
||||
LocalDateTime time = LocalDateTime.of(2026, 9, 13, 4, 0);
|
||||
java.util.List<Map<String, Object>> rows = new java.util.ArrayList<>(Arrays.asList(
|
||||
row(126, time.plusMinutes(1), 1), row(125, time, 2), row(126, time, 3)));
|
||||
committed(writer, rows);
|
||||
java.util.List<String> first = new java.util.ArrayList<>(locks);
|
||||
locks.clear();
|
||||
java.util.Collections.reverse(rows);
|
||||
committed(writer, rows);
|
||||
assertEquals(first, locks);
|
||||
assertEquals(3, locks.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupsRowsByDeviceAndEventMinute() {
|
||||
JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class);
|
||||
LateAlarmBucketWriter writer = new LateAlarmBucketWriter(jdbcTemplate);
|
||||
LateAlarmBucketWriter writer = writer(jdbcTemplate);
|
||||
ReflectionTestUtils.setField(writer, "enabled", true);
|
||||
|
||||
writer.record(
|
||||
committed(writer,
|
||||
Arrays.asList(
|
||||
row(126, LocalDateTime.of(2026, 9, 4, 10, 1, 2), 3),
|
||||
row(126, LocalDateTime.of(2026, 9, 4, 10, 1, 59), 4),
|
||||
@@ -41,13 +89,37 @@ class LateAlarmBucketWriterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAlarmRowsWithoutStableTimes() {
|
||||
LateAlarmBucketWriter writer = new LateAlarmBucketWriter(mock(JdbcTemplate.class));
|
||||
void invalidNotificationDoesNotAbortAlarmTransaction() {
|
||||
LateAlarmBucketWriter writer = writer(mock(JdbcTemplate.class));
|
||||
ReflectionTestUtils.setField(writer, "enabled", true);
|
||||
Map<String, Object> invalid = new HashMap<>();
|
||||
invalid.put("device_id", 126);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> writer.record(Arrays.asList(invalid)));
|
||||
org.junit.jupiter.api.Assertions.assertDoesNotThrow(() -> committed(writer, Arrays.asList(invalid)));
|
||||
assertEquals(1L, writer.status().get("lost_tasks_total"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void commitOnlyEnqueuesRollbackNeverEnqueuesAndDatabaseFailureOnlyRetriesBackground() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
LateAlarmBucketWriter writer = writer(jdbc);
|
||||
java.util.List<Map<String, Object>> rows = Arrays.asList(row(126, LocalDateTime.now(), 1));
|
||||
transaction.execute(status -> { writer.record(rows); status.setRollbackOnly(); return null; });
|
||||
assertEquals(0L, writer.status().get("enqueued_total"));
|
||||
transaction.execute(status -> { writer.record(rows); return null; });
|
||||
org.mockito.Mockito.verifyNoInteractions(jdbc);
|
||||
org.mockito.Mockito.doThrow(new IllegalStateException("database unavailable"))
|
||||
.when(jdbc).update(anyString(), any(), any(), any(), any(), any(), any());
|
||||
BestEffortAuxiliaryQueue queue = (BestEffortAuxiliaryQueue) ReflectionTestUtils.getField(writer, "queue");
|
||||
org.junit.jupiter.api.Assertions.assertDoesNotThrow(queue::drain);
|
||||
assertEquals(1L, writer.status().get("failures_total"));
|
||||
assertEquals(1, writer.status().get("pending_tasks"));
|
||||
assertEquals(0L, writer.status().get("lost_tasks_total"));
|
||||
Object current = ReflectionTestUtils.getField(queue, "current");
|
||||
ReflectionTestUtils.setField(current, "retryAt", 0L);
|
||||
org.mockito.Mockito.doReturn(1).when(jdbc).update(anyString(), any(), any(), any(), any(), any(), any());
|
||||
queue.drain();
|
||||
assertEquals(1L, writer.status().get("completed_total"));
|
||||
}
|
||||
|
||||
private Map<String, Object> row(int deviceId, LocalDateTime eventTime, int receiveSecond) {
|
||||
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class RawLaneFieldLimiterTest {
|
||||
@Test
|
||||
void springDefaultIsTwoKiBAndExplicitOverrideWorks() {
|
||||
checkSpringLimit(null, 2048);
|
||||
checkSpringLimit("4096", 4096);
|
||||
checkSpringLimit("0", 0);
|
||||
}
|
||||
|
||||
private void checkSpringLimit(String override, int expected) {
|
||||
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
|
||||
Map<String, Object> properties = new HashMap<>();
|
||||
properties.put("spring.kafka.consumer.topic", "raw");
|
||||
if (override != null) properties.put("syslog.raw-listener.field-max-utf8-bytes", override);
|
||||
context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test", properties));
|
||||
context.register(RawLaneFieldLimiter.class);
|
||||
context.refresh();
|
||||
RawLaneFieldLimiter limiter = context.getBean(RawLaneFieldLimiter.class);
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
String content = repeat("a", 5000);
|
||||
row.put("custom_field", content);
|
||||
limiter.truncateRow(row);
|
||||
assertEquals(expected == 0 ? content : expected,
|
||||
expected == 0 ? row.get("custom_field") : bytes(row.get("custom_field")));
|
||||
assertEquals(expected != 0, limiter.appliesTo("raw", null));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void truncatesCustomTextByUtf8WithMarkerAndPreservesTypesAndIdentity() {
|
||||
RawLaneFieldLimiter limiter = new RawLaneFieldLimiter(2048, "raw");
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
String content = repeat("中文🙂", 1000);
|
||||
row.put("custom_field", content);
|
||||
row.put("id", content);
|
||||
row.put("event_level", "HIGH");
|
||||
row.put("number", 123L);
|
||||
row.put("nothing", null);
|
||||
byte[] binary = new byte[3000];
|
||||
row.put("binary", binary);
|
||||
row.put("exact", repeat("a", 2048));
|
||||
row.put("short", "短字段");
|
||||
limiter.truncateRow(row);
|
||||
String stored = (String) row.get("custom_field");
|
||||
assertTrue(bytes(stored) <= 2048);
|
||||
assertTrue(stored.endsWith("...[HB_XDR_TRUNCATED original_utf8_bytes=10000]"));
|
||||
assertEquals(stored, new String(stored.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
|
||||
assertEquals(content, row.get("id"));
|
||||
assertEquals("HIGH", row.get("event_level"));
|
||||
assertEquals(123L, row.get("number"));
|
||||
assertNull(row.get("nothing"));
|
||||
assertSame(binary, row.get("binary"));
|
||||
assertEquals(repeat("a", 2048), row.get("exact"));
|
||||
assertEquals("短字段", row.get("short"));
|
||||
limiter.truncateRow(row);
|
||||
assertEquals(stored, row.get("custom_field"), "重复处理不能重复追加标记");
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyOriginalRawTopicAppliesIncludingRetryAndReplay() {
|
||||
RawLaneFieldLimiter limiter = new RawLaneFieldLimiter(2048, "custom-raw");
|
||||
assertTrue(limiter.appliesTo("custom-raw", null));
|
||||
assertTrue(limiter.appliesTo("retry", "custom-raw"));
|
||||
assertTrue(limiter.appliesTo("replay", "custom-raw"));
|
||||
assertFalse(limiter.appliesTo("custom-large", null));
|
||||
assertFalse(limiter.appliesTo("retry", "custom-large"));
|
||||
assertFalse(limiter.appliesTo("custom-raw", "custom-large"));
|
||||
assertFalse(limiter.appliesTo("retry", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonNormalContentLimitedButIdentityUnchanged() {
|
||||
RawLaneFieldLimiter limiter = new RawLaneFieldLimiter(2048, "raw");
|
||||
SyslogNonNormalMessage message = new SyslogNonNormalMessage();
|
||||
String content = repeat("x", 4096);
|
||||
message.setSyslogMessage(content);
|
||||
message.setHeaderMessage(content);
|
||||
message.setReasonDetail(content);
|
||||
message.setSyslogUuid("stable-id");
|
||||
limiter.truncateNonNormal(message);
|
||||
assertEquals(2048, bytes(message.getSyslogMessage()));
|
||||
assertEquals(2048, bytes(message.getHeaderMessage()));
|
||||
assertEquals(2048, bytes(message.getReasonDetail()));
|
||||
assertEquals("stable-id", message.getSyslogUuid());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatesMarkerBudget() {
|
||||
assertThrows(IllegalArgumentException.class, () -> new RawLaneFieldLimiter(-1, "raw"));
|
||||
assertThrows(IllegalArgumentException.class, () -> new RawLaneFieldLimiter(63, "raw"));
|
||||
assertDoesNotThrow(() -> new RawLaneFieldLimiter(64, "raw"));
|
||||
}
|
||||
|
||||
private static int bytes(Object text) { return ((String) text).getBytes(StandardCharsets.UTF_8).length; }
|
||||
private static String repeat(String text, int count) {
|
||||
StringBuilder value = new StringBuilder();
|
||||
for (int i = 0; i < count; i++) value.append(text);
|
||||
return value.toString();
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
class RawLogCaptureClusterStoreWiringTest {
|
||||
|
||||
@Test
|
||||
void usesHttpObjectMapperWhenApplicationHasMultipleObjectMappers() {
|
||||
try (AnnotationConfigApplicationContext context =
|
||||
new AnnotationConfigApplicationContext(TestConfiguration.class,
|
||||
RawLogCaptureClusterStore.class)) {
|
||||
RawLogCaptureClusterStore store = context.getBean(RawLogCaptureClusterStore.class);
|
||||
|
||||
assertSame(context.getBean("httpObjectMapper"),
|
||||
ReflectionTestUtils.getField(store, "mapper"));
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class TestConfiguration {
|
||||
@Bean
|
||||
ObjectMapper objectMapper() {
|
||||
return new ObjectMapper();
|
||||
}
|
||||
|
||||
@Bean
|
||||
ObjectMapper httpObjectMapper() {
|
||||
return new ObjectMapper();
|
||||
}
|
||||
|
||||
@Bean
|
||||
StringRedisTemplate stringRedisTemplate() {
|
||||
return mock(StringRedisTemplate.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
package com.common.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class RawLogCaptureServiceTest {
|
||||
|
||||
@Test
|
||||
void keepsFirstMessagesThenReplacesOldestNormalWithLaterAnomalies() {
|
||||
MutableClock clock = new MutableClock(1_700_000_000_000L);
|
||||
RawLogCaptureService service = new RawLogCaptureService(clock);
|
||||
RawLogCaptureService.CaptureSnapshot started = service.start(7L, 60, 3);
|
||||
|
||||
receive(service, clock, 7L, "e1");
|
||||
receive(service, clock, 7L, "e2");
|
||||
receive(service, clock, 7L, "e3");
|
||||
receive(service, clock, 7L, "e4");
|
||||
assertEquals(Arrays.asList("e1", "e2", "e3"), ids(service.get(started.getSessionId())));
|
||||
|
||||
fail(service, clock, 7L, "e4");
|
||||
fail(service, clock, 7L, "e5");
|
||||
fail(service, clock, 7L, "e6");
|
||||
RawLogCaptureService.CaptureSnapshot anomalies = service.get(started.getSessionId());
|
||||
|
||||
assertEquals(Arrays.asList("e4", "e5", "e6"), ids(anomalies));
|
||||
assertEquals(3, anomalies.getRetainedAnomalyCount());
|
||||
assertEquals(3L, anomalies.getReplacementCount());
|
||||
|
||||
fail(service, clock, 7L, "e7");
|
||||
assertEquals(Arrays.asList("e4", "e5", "e6"),
|
||||
ids(service.get(started.getSessionId())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void upgradesSelectedMessageToAnomalyWithoutReplacement() {
|
||||
MutableClock clock = new MutableClock(1_700_000_000_000L);
|
||||
RawLogCaptureService service = new RawLogCaptureService(clock);
|
||||
RawLogCaptureService.CaptureSnapshot started = service.start(7L, 60, 2);
|
||||
|
||||
receive(service, clock, 7L, "e1");
|
||||
receive(service, clock, 7L, "e2");
|
||||
fail(service, clock, 7L, "e2");
|
||||
|
||||
RawLogCaptureService.CaptureSnapshot snapshot = service.get(started.getSessionId());
|
||||
assertEquals(Arrays.asList("e1", "e2"), ids(snapshot));
|
||||
assertEquals(1, snapshot.getRetainedAnomalyCount());
|
||||
assertEquals(0L, snapshot.getReplacementCount());
|
||||
assertFalse(snapshot.getMessages().get(0).isAnomaly());
|
||||
assertTrue(snapshot.getMessages().get(1).isAnomaly());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isolatesDevicesAndAcceptsLateOutcomeOnlyDuringSettlingPeriod() {
|
||||
MutableClock clock = new MutableClock(1_700_000_000_000L);
|
||||
RawLogCaptureService service = new RawLogCaptureService(clock);
|
||||
RawLogCaptureService.CaptureSnapshot started = service.start(7L, 2, 1);
|
||||
long observedInsideWindow = clock.millis();
|
||||
|
||||
receive(service, clock, 8L, "other-device");
|
||||
receive(service, clock, 7L, "normal");
|
||||
clock.advanceMillis(3_000L);
|
||||
assertEquals("DRAINING", service.get(started.getSessionId()).getStatus());
|
||||
|
||||
service.observeFailure(observedInsideWindow, 7L, 1L, "late-error", "topic",
|
||||
LocalDateTime.ofInstant(Instant.ofEpochMilli(observedInsideWindow), ZoneOffset.UTC),
|
||||
"raw-late-error", "RULE_PROCESSING", "DLT_PUBLISHED",
|
||||
new IllegalStateException("bad json"));
|
||||
RawLogCaptureService.CaptureSnapshot draining = service.get(started.getSessionId());
|
||||
assertEquals(Arrays.asList("late-error"), ids(draining));
|
||||
assertEquals(1L, draining.getReplacementCount());
|
||||
|
||||
clock.advanceMillis(31_000L);
|
||||
assertEquals("COMPLETED", service.get(started.getSessionId()).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatesHardApiLimits() {
|
||||
RawLogCaptureService service = new RawLogCaptureService(
|
||||
new MutableClock(1_700_000_000_000L));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.start(0L, 1, 1));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.start(1L, 601, 1));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.start(1L, 1, 51));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergesCandidatesAcrossConsumerInstancesBeforeApplyingAnomalyReplacement() {
|
||||
List<RawLogCaptureService.CapturedLogSnapshot> first = Arrays.asList(
|
||||
snapshot(2, "a2", false), snapshot(3, "a3", false), snapshot(4, "a4", false),
|
||||
snapshot(1, "b1", false), snapshot(100, "b100", false),
|
||||
snapshot(101, "b101", false));
|
||||
List<RawLogCaptureService.CapturedLogSnapshot> anomalies =
|
||||
Arrays.asList(snapshot(200, "a200", true));
|
||||
|
||||
List<RawLogCaptureService.CapturedLogSnapshot> selected =
|
||||
RawLogCaptureService.mergeCandidates(first, anomalies, 3);
|
||||
|
||||
assertEquals(Arrays.asList("a2", "a3", "a200"), selected.stream()
|
||||
.map(RawLogCaptureService.CapturedLogSnapshot::getEventId)
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
private static RawLogCaptureService.CapturedLogSnapshot snapshot(
|
||||
long sequence, String eventId, boolean anomaly) {
|
||||
return new RawLogCaptureService.CapturedLogSnapshot(sequence, eventId, 7L, 1L,
|
||||
"topic", null, "2026-09-14T00:00:00Z",
|
||||
anomaly ? "NON_NORMAL" : "SUCCESS", anomaly,
|
||||
anomaly ? "JSON解析异常" : null, null, null, "raw-" + eventId);
|
||||
}
|
||||
|
||||
private static void receive(RawLogCaptureService service, Clock clock,
|
||||
long deviceId, String eventId) {
|
||||
service.observeReceived(clock.millis(), deviceId, 1L, eventId, "topic",
|
||||
LocalDateTime.ofInstant(Instant.ofEpochMilli(clock.millis()), ZoneOffset.UTC),
|
||||
"raw-" + eventId);
|
||||
}
|
||||
|
||||
private static void fail(RawLogCaptureService service, Clock clock,
|
||||
long deviceId, String eventId) {
|
||||
service.observeFailure(clock.millis(), deviceId, 1L, eventId, "topic",
|
||||
LocalDateTime.ofInstant(Instant.ofEpochMilli(clock.millis()), ZoneOffset.UTC),
|
||||
"raw-" + eventId, "RULE_PROCESSING", "DLT_PUBLISHED",
|
||||
new IllegalArgumentException("broken"));
|
||||
}
|
||||
|
||||
private static List<String> ids(RawLogCaptureService.CaptureSnapshot snapshot) {
|
||||
return snapshot.getMessages().stream()
|
||||
.map(RawLogCaptureService.CapturedLogSnapshot::getEventId)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static final class MutableClock extends Clock {
|
||||
private long millis;
|
||||
|
||||
private MutableClock(long millis) { this.millis = millis; }
|
||||
private void advanceMillis(long value) { millis += value; }
|
||||
@Override public ZoneId getZone() { return ZoneOffset.UTC; }
|
||||
@Override public Clock withZone(ZoneId zone) { return this; }
|
||||
@Override public Instant instant() { return Instant.ofEpochMilli(millis); }
|
||||
@Override public long millis() { return millis; }
|
||||
}
|
||||
}
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.kafka.core.KafkaTemplate;
|
||||
import org.springframework.kafka.support.SendResult;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
|
||||
import org.springframework.transaction.support.DefaultTransactionStatus;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.util.concurrent.SettableListenableFuture;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class StatsProjectionAsyncPublisherTest {
|
||||
private final KafkaTemplate<String, String> kafka = mock(KafkaTemplate.class);
|
||||
private final TransactionTemplate transaction = new TransactionTemplate(new TestTransactionManager());
|
||||
|
||||
@AfterEach
|
||||
void cleanup() { TransactionSynchronizationManager.clear(); }
|
||||
|
||||
@Test
|
||||
void productionConstructorUsesDedicatedProducerWithExistingKafkaSettings() {
|
||||
org.springframework.boot.autoconfigure.kafka.KafkaProperties properties =
|
||||
new org.springframework.boot.autoconfigure.kafka.KafkaProperties();
|
||||
properties.setBootstrapServers(java.util.Collections.singletonList("broker.example:9092"));
|
||||
properties.getProperties().put("security.protocol", "SASL_PLAINTEXT");
|
||||
properties.getProducer().setAcks("all");
|
||||
StatsProjectionAsyncPublisher publisher = new StatsProjectionAsyncPublisher(properties, new ObjectMapper(), 10, 10);
|
||||
org.springframework.kafka.core.DefaultKafkaProducerFactory<?, ?> factory =
|
||||
(org.springframework.kafka.core.DefaultKafkaProducerFactory<?, ?>)
|
||||
ReflectionTestUtils.getField(publisher, "ownedProducerFactory");
|
||||
assertNotNull(factory);
|
||||
assertEquals("SASL_PLAINTEXT", factory.getConfigurationProperties().get("security.protocol"));
|
||||
assertEquals("all", factory.getConfigurationProperties().get("acks"));
|
||||
assertEquals("syslog-stats-projection-memory", factory.getConfigurationProperties().get("client.id"));
|
||||
assertEquals(java.util.Collections.singletonList("broker.example:9092"),
|
||||
factory.getConfigurationProperties().get("bootstrap.servers"));
|
||||
publisher.stop(); // 不创建连接即可构造/销毁,未依赖真实Kafka。
|
||||
}
|
||||
|
||||
@Test
|
||||
void commitOnlyOffersAndRollbackNeverEnqueues() throws Exception {
|
||||
StatsProjectionAsyncPublisher publisher = publisher(10, 10);
|
||||
StatsProjectionOutboxEvent event = event();
|
||||
transaction.execute(status -> {
|
||||
publisher.enqueueAfterCommit(event, 1);
|
||||
assertEquals(0, metric(publisher, "pending_events"));
|
||||
verifyNoInteractions(kafka);
|
||||
return null;
|
||||
});
|
||||
assertEquals(1, metric(publisher, "pending_events"));
|
||||
verifyNoInteractions(kafka); // 即使Kafka发送会阻塞,事实提交也不调用它。
|
||||
transaction.execute(status -> {
|
||||
publisher.enqueueAfterCommit(event(), 1);
|
||||
status.setRollbackOnly();
|
||||
return null;
|
||||
});
|
||||
assertEquals(1, metric(publisher, "enqueued_total"));
|
||||
SettableListenableFuture<SendResult<String, String>> success = new SettableListenableFuture<>();
|
||||
success.set(null);
|
||||
when(kafka.send(anyString(), anyString(), anyString())).thenReturn(success);
|
||||
publisher.flush();
|
||||
assertEquals(1, metric(publisher, "published_total"));
|
||||
assertEquals(0, metric(publisher, "pending_groups"));
|
||||
ArgumentCaptor<String> payload = ArgumentCaptor.forClass(String.class);
|
||||
verify(kafka).send(eq("stats-topic"), eq(StatsProjectionOutboxEvent.KAFKA_KEY), payload.capture());
|
||||
StatsProjectionOutboxEvent sent = new ObjectMapper().readValue(payload.getValue(), StatsProjectionOutboxEvent.class);
|
||||
assertFalse(sent.isOutboxBacked());
|
||||
assertEquals(event.getEventId(), sent.getEventId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void kafkaFailureRetriesSameEventWhileQueueOverflowLetsFactCommit() {
|
||||
StatsProjectionAsyncPublisher publisher = publisher(1, 10);
|
||||
SettableListenableFuture<SendResult<String, String>> failure = new SettableListenableFuture<>();
|
||||
failure.setException(new IllegalStateException("Kafka unavailable"));
|
||||
SettableListenableFuture<SendResult<String, String>> success = new SettableListenableFuture<>();
|
||||
success.set(null);
|
||||
when(kafka.send(anyString(), anyString(), anyString())).thenReturn(failure, success, success);
|
||||
commit(publisher);
|
||||
assertDoesNotThrow(publisher::flush);
|
||||
assertEquals(1, metric(publisher, "publish_failures_total"));
|
||||
commit(publisher);
|
||||
commit(publisher); // queue=1,另有一个正在重试;第三条只损失统计。
|
||||
assertEquals(2, metric(publisher, "pending_events"));
|
||||
assertEquals(1, metric(publisher, "dropped_events_total"));
|
||||
assertEquals(1, metric(publisher, "dropped_fact_rows_total"));
|
||||
Object pending = ReflectionTestUtils.getField(publisher, "inFlight");
|
||||
ReflectionTestUtils.setField(pending, "retryAt", 0L);
|
||||
publisher.flush();
|
||||
assertEquals(2, metric(publisher, "published_total"));
|
||||
assertEquals(0, metric(publisher, "pending_groups"));
|
||||
ArgumentCaptor<String> payload = ArgumentCaptor.forClass(String.class);
|
||||
verify(kafka, times(3)).send(anyString(), anyString(), payload.capture());
|
||||
assertEquals(payload.getAllValues().get(0), payload.getAllValues().get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blockedBackgroundSendDoesNotBlockNextCommit() throws Exception {
|
||||
StatsProjectionAsyncPublisher publisher = publisher(1, 10);
|
||||
SettableListenableFuture<SendResult<String, String>> blocked = new SettableListenableFuture<>();
|
||||
java.util.concurrent.CountDownLatch entered = new java.util.concurrent.CountDownLatch(1);
|
||||
when(kafka.send(anyString(), anyString(), anyString())).thenAnswer(call -> {
|
||||
entered.countDown();
|
||||
return blocked;
|
||||
});
|
||||
commit(publisher);
|
||||
CompletableFuture<Void> worker = CompletableFuture.runAsync(publisher::flush);
|
||||
try {
|
||||
assertTrue(entered.await(3, TimeUnit.SECONDS));
|
||||
// 使用另一线程+有界等待,防止错误地共享flush锁使测试永久挂住。
|
||||
CompletableFuture.runAsync(() -> { commit(publisher); commit(publisher); }).get(2, TimeUnit.SECONDS);
|
||||
assertEquals(1, metric(publisher, "dropped_events_total"));
|
||||
} finally {
|
||||
blocked.set(null);
|
||||
worker.get(3, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupBudgetIsBoundedAndReleasedAfterSend() {
|
||||
StatsProjectionAsyncPublisher publisher = publisher(10, 1);
|
||||
commit(publisher);
|
||||
commit(publisher);
|
||||
assertEquals(1, metric(publisher, "pending_groups"));
|
||||
assertEquals(1, metric(publisher, "dropped_events_total"));
|
||||
SettableListenableFuture<SendResult<String, String>> success = new SettableListenableFuture<>();
|
||||
success.set(null);
|
||||
when(kafka.send(anyString(), anyString(), anyString())).thenReturn(success);
|
||||
publisher.flush();
|
||||
commit(publisher);
|
||||
assertEquals(2, metric(publisher, "enqueued_total"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingTransactionDisabledPublisherAndShutdownFailOpen() {
|
||||
StatsProjectionAsyncPublisher publisher = publisher(10, 10);
|
||||
assertDoesNotThrow(() -> publisher.enqueueAfterCommit(event(), 1));
|
||||
assertEquals(1, metric(publisher, "dropped_events_total"));
|
||||
ReflectionTestUtils.setField(publisher, "enabled", false);
|
||||
commit(publisher);
|
||||
ReflectionTestUtils.setField(publisher, "enabled", true);
|
||||
publisher.stop();
|
||||
commit(publisher);
|
||||
assertEquals(3, metric(publisher, "dropped_events_total"));
|
||||
assertEquals(0, metric(publisher, "pending_events"));
|
||||
verifyNoInteractions(kafka);
|
||||
}
|
||||
|
||||
@Test
|
||||
void directStatisticsAggregationFailureDoesNotRollbackFacts() {
|
||||
StatsProjectionAsyncPublisher publisher = publisher(10, 10);
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
DirectStatsProjectionWriter writer = new DirectStatsProjectionWriter(jdbc,
|
||||
new StatsWriteModeProvider("DIRECT"), new DirectStatsWriteMetrics(),
|
||||
mock(StatsMaterializationPublisher.class), publisher);
|
||||
ReflectionTestUtils.setField(writer, "businessZone", "invalid-zone");
|
||||
assertDoesNotThrow(() -> transaction.execute(status -> {
|
||||
writer.writeStandardizedRow(row());
|
||||
assertFalse(status.isRollbackOnly());
|
||||
return null;
|
||||
}));
|
||||
assertEquals(1, metric(publisher, "dropped_events_total"));
|
||||
verifyNoInteractions(jdbc, kafka);
|
||||
}
|
||||
|
||||
@Test
|
||||
void directNonNormalUpdateAndDisabledPublishingNeverUseStatisticsSql() {
|
||||
StatsProjectionAsyncPublisher publisher = publisher(10, 10);
|
||||
ReflectionTestUtils.setField(publisher, "enabled", false);
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
DirectStatsProjectionWriter writer = new DirectStatsProjectionWriter(jdbc,
|
||||
new StatsWriteModeProvider("DIRECT"), new DirectStatsWriteMetrics(),
|
||||
mock(StatsMaterializationPublisher.class), publisher);
|
||||
ReflectionTestUtils.setField(writer, "businessZone", "Asia/Shanghai");
|
||||
com.common.entity.SyslogNonNormalMessage old = new com.common.entity.SyslogNonNormalMessage();
|
||||
old.setDeviceId(7);
|
||||
old.setCreatedAt(java.time.OffsetDateTime.now());
|
||||
com.common.entity.SyslogNonNormalMessage patch = new com.common.entity.SyslogNonNormalMessage();
|
||||
patch.setDeviceId(8);
|
||||
transaction.execute(status -> {
|
||||
writer.writeStandardizedRow(row());
|
||||
writer.writeNonNormalInsert(old);
|
||||
writer.writeNonNormalUpdate(old, patch);
|
||||
return null;
|
||||
});
|
||||
assertEquals(3, metric(publisher, "dropped_events_total"));
|
||||
verifyNoInteractions(jdbc, kafka);
|
||||
}
|
||||
|
||||
private StatsProjectionAsyncPublisher publisher(int capacity, long groups) {
|
||||
StatsProjectionAsyncPublisher publisher = new StatsProjectionAsyncPublisher(kafka, new ObjectMapper(), capacity, groups);
|
||||
ReflectionTestUtils.setField(publisher, "enabled", true);
|
||||
ReflectionTestUtils.setField(publisher, "topic", "stats-topic");
|
||||
ReflectionTestUtils.setField(publisher, "timeoutMs", 10000L);
|
||||
return publisher;
|
||||
}
|
||||
|
||||
private void commit(StatsProjectionAsyncPublisher publisher) {
|
||||
transaction.execute(status -> { publisher.enqueueAfterCommit(event(), 1); return null; });
|
||||
}
|
||||
|
||||
private static Map<String, Object> row() {
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
row.put("created_at", LocalDateTime.of(2026, 9, 13, 8, 0));
|
||||
row.put("device_id", 7L);
|
||||
return row;
|
||||
}
|
||||
|
||||
private static StatsProjectionOutboxEvent event() {
|
||||
return StatsProjectionOutboxEvent.fromAccumulator(new DirectStatsAccumulator().addStandardizedRow(row()));
|
||||
}
|
||||
|
||||
private static long metric(StatsProjectionAsyncPublisher publisher, String key) {
|
||||
return ((Number) publisher.status().get(key)).longValue();
|
||||
}
|
||||
|
||||
private static class TestTransactionManager extends AbstractPlatformTransactionManager {
|
||||
protected Object doGetTransaction() { return new Object(); }
|
||||
protected void doBegin(Object transaction, TransactionDefinition definition) { }
|
||||
protected void doCommit(DefaultTransactionStatus status) { }
|
||||
protected void doRollback(DefaultTransactionStatus status) { }
|
||||
}
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.SimpleTransactionStatus;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class StatsProjectionAsyncTest {
|
||||
@AfterEach
|
||||
void clearTransactionState() {
|
||||
TransactionSynchronizationManager.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxEventAggregatesOneFactBatchByDimension() {
|
||||
LocalDateTime time = LocalDateTime.of(2026, 9, 12, 8, 0);
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
for (long ruleId : Arrays.asList(11L, 12L, 11L)) {
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
row.put("created_at", time);
|
||||
row.put("log_time", time.plusMinutes(ruleId));
|
||||
row.put("device_id", 7L);
|
||||
row.put("normalize_rule_id", ruleId);
|
||||
rows.add(row);
|
||||
}
|
||||
|
||||
StatsProjectionOutboxEvent event = StatsProjectionOutboxEvent.fromAccumulator(
|
||||
new DirectStatsAccumulator().addStandardizedRows(rows));
|
||||
|
||||
event.validate();
|
||||
assertEquals(1, event.getDevices().size());
|
||||
assertEquals(3L, event.getDevices().get(0).getParseDelta());
|
||||
assertEquals(2, event.getRules().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxWriterRequiresAndUsesFactTransaction() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
StatsProjectionOutboxWriter writer = new StatsProjectionOutboxWriter(jdbc, new ObjectMapper());
|
||||
ReflectionTestUtils.setField(writer, "enabled", true);
|
||||
ReflectionTestUtils.setField(writer, "outboxTable", "stats_projection_outbox");
|
||||
StatsProjectionOutboxEvent event = oneDeviceEvent("event-1");
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> writer.append(event));
|
||||
|
||||
TransactionSynchronizationManager.setActualTransactionActive(true);
|
||||
writer.append(event);
|
||||
verify(jdbc).update(org.mockito.ArgumentMatchers.contains("INSERT INTO stats_projection_outbox"),
|
||||
org.mockito.ArgumentMatchers.eq("event-1"),
|
||||
org.mockito.ArgumentMatchers.eq(StatsProjectionOutboxEvent.SCHEMA),
|
||||
org.mockito.ArgumentMatchers.anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void projectionConsumerAppliesFreshEventAndRecordsIdempotencyMarker() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(org.mockito.ArgumentMatchers.anyString(),
|
||||
org.mockito.ArgumentMatchers.eq(String.class), org.mockito.ArgumentMatchers.<Object>any()))
|
||||
.thenReturn(Collections.emptyList());
|
||||
PlatformTransactionManager manager = mock(PlatformTransactionManager.class);
|
||||
when(manager.getTransaction(any(TransactionDefinition.class))).thenReturn(new SimpleTransactionStatus());
|
||||
StatsMaterializationPublisher publisher = mock(StatsMaterializationPublisher.class);
|
||||
StatsProjectionDeltaConsumer consumer = new StatsProjectionDeltaConsumer(
|
||||
jdbc, manager, new ObjectMapper(), publisher);
|
||||
configure(consumer);
|
||||
|
||||
StatsProjectionDeltaConsumer.ApplyResult result = consumer.applyWithRetry(
|
||||
Collections.singletonList(oneDeviceEvent("event-1")));
|
||||
|
||||
assertEquals(1, result.appliedEvents);
|
||||
assertEquals(1, result.deviceGroups);
|
||||
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
|
||||
verify(jdbc, times(3)).batchUpdate(sql.capture(), anyList());
|
||||
assertTrue(sql.getAllValues().get(0).contains("MERGE INTO device_daily_stats"));
|
||||
assertTrue(sql.getAllValues().get(1).contains("stats_projection_applied_event"));
|
||||
assertTrue(sql.getAllValues().get(2).contains("SET status='APPLIED'"));
|
||||
verify(publisher).enqueueAfterCommit(org.mockito.ArgumentMatchers.anyCollection());
|
||||
verify(manager).commit(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void projectionConsumerDoesNotApplyDuplicateDeltaTwice() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(org.mockito.ArgumentMatchers.anyString(),
|
||||
org.mockito.ArgumentMatchers.eq(String.class), org.mockito.ArgumentMatchers.<Object>any()))
|
||||
.thenReturn(Collections.singletonList("event-1"));
|
||||
PlatformTransactionManager manager = mock(PlatformTransactionManager.class);
|
||||
when(manager.getTransaction(any(TransactionDefinition.class))).thenReturn(new SimpleTransactionStatus());
|
||||
StatsMaterializationPublisher publisher = mock(StatsMaterializationPublisher.class);
|
||||
StatsProjectionDeltaConsumer consumer = new StatsProjectionDeltaConsumer(
|
||||
jdbc, manager, new ObjectMapper(), publisher);
|
||||
configure(consumer);
|
||||
|
||||
StatsProjectionDeltaConsumer.ApplyResult result = consumer.applyWithRetry(
|
||||
Collections.singletonList(oneDeviceEvent("event-1")));
|
||||
|
||||
assertEquals(0, result.appliedEvents);
|
||||
assertEquals(1, result.duplicates);
|
||||
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
|
||||
verify(jdbc).batchUpdate(sql.capture(), anyList());
|
||||
assertTrue(sql.getValue().contains("SET status='APPLIED'"));
|
||||
}
|
||||
|
||||
private StatsProjectionOutboxEvent oneDeviceEvent(String eventId) {
|
||||
DirectStatsAccumulator accumulator = new DirectStatsAccumulator();
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
row.put("created_at", LocalDate.of(2026, 9, 12));
|
||||
row.put("log_time", LocalDateTime.of(2026, 9, 12, 8, 0));
|
||||
row.put("device_id", 7L);
|
||||
StatsProjectionOutboxEvent event = StatsProjectionOutboxEvent.fromAccumulator(
|
||||
accumulator.addStandardizedRow(row));
|
||||
event.setEventId(eventId);
|
||||
return event;
|
||||
}
|
||||
|
||||
@Test
|
||||
void memoryEventUpdatesProjectionAndDedupMarkerWithoutTouchingOutbox() throws Exception {
|
||||
StatsProjectionOutboxEvent event = oneDeviceEvent("memory-1");
|
||||
event.setOutboxBacked(false);
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
event = mapper.readValue(mapper.writeValueAsString(event), StatsProjectionOutboxEvent.class);
|
||||
org.junit.jupiter.api.Assertions.assertFalse(event.isOutboxBacked());
|
||||
assertTrue(mapper.readValue("{\"eventId\":\"legacy\"}", StatsProjectionOutboxEvent.class).isOutboxBacked());
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
PlatformTransactionManager manager = mock(PlatformTransactionManager.class);
|
||||
when(manager.getTransaction(any(TransactionDefinition.class))).thenReturn(new SimpleTransactionStatus());
|
||||
StatsProjectionDeltaConsumer consumer = new StatsProjectionDeltaConsumer(
|
||||
jdbc, manager, mapper, mock(StatsMaterializationPublisher.class));
|
||||
configure(consumer);
|
||||
consumer.applyWithRetry(Collections.singletonList(event));
|
||||
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
|
||||
verify(jdbc, times(2)).batchUpdate(sql.capture(), anyList());
|
||||
assertTrue(sql.getAllValues().get(0).contains("MERGE INTO device_daily_stats"));
|
||||
assertTrue(sql.getAllValues().get(1).contains("stats_projection_applied_event"));
|
||||
when(jdbc.queryForList(org.mockito.ArgumentMatchers.anyString(),
|
||||
org.mockito.ArgumentMatchers.eq(String.class), org.mockito.ArgumentMatchers.<Object>any()))
|
||||
.thenReturn(Collections.singletonList("memory-1"));
|
||||
assertEquals(1, consumer.applyWithRetry(Collections.singletonList(event)).duplicates);
|
||||
verify(jdbc, times(2)).batchUpdate(org.mockito.ArgumentMatchers.anyString(), anyList());
|
||||
}
|
||||
|
||||
private void configure(StatsProjectionDeltaConsumer consumer) {
|
||||
ReflectionTestUtils.setField(consumer, "enabled", true);
|
||||
ReflectionTestUtils.setField(consumer, "appliedTable", "stats_projection_applied_event");
|
||||
ReflectionTestUtils.setField(consumer, "outboxTable", "stats_projection_outbox");
|
||||
ReflectionTestUtils.setField(consumer, "deviceTable", "device_daily_stats");
|
||||
ReflectionTestUtils.setField(consumer, "ruleTable", "normalize_rule_daily_stats");
|
||||
ReflectionTestUtils.setField(consumer, "transactionTimeoutSeconds", 45);
|
||||
ReflectionTestUtils.setField(consumer, "maxConcurrencyRetries", 3);
|
||||
ReflectionTestUtils.setField(consumer, "retryBackoffMs", 0L);
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.config.CacheConfig;
|
||||
import com.config.WebConfig;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.mock.env.MockEnvironment;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** 使用实际配置创建两个同类型Bean,覆盖现场启动时的构造器自动装配。 */
|
||||
class StatsProjectionPublisherWiringTest {
|
||||
@Test
|
||||
void startsWithCacheAndHttpMappersWithoutChangingSharedSerialization() {
|
||||
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
|
||||
context.setEnvironment(new MockEnvironment()
|
||||
.withProperty("stats.projection-async.topic", "test.STATS.PROJECTION"));
|
||||
context.registerBean("objectMapper", ObjectMapper.class, () -> new CacheConfig().objectMapper());
|
||||
context.registerBean("httpObjectMapper", ObjectMapper.class, () -> new WebConfig().httpObjectMapper());
|
||||
context.registerBean(KafkaProperties.class);
|
||||
context.register(StatsProjectionAsyncPublisher.class);
|
||||
assertDoesNotThrow(context::refresh);
|
||||
assertEquals(2, context.getBeansOfType(ObjectMapper.class).size());
|
||||
StatsProjectionAsyncPublisher publisher = context.getBean(StatsProjectionAsyncPublisher.class);
|
||||
ObjectMapper shared = context.getBean("objectMapper", ObjectMapper.class);
|
||||
ObjectMapper copied = (ObjectMapper) ReflectionTestUtils.getField(publisher, "mapper");
|
||||
assertNotSame(shared, copied);
|
||||
assertEquals(shared.getRegisteredModuleIds(), copied.getRegisteredModuleIds());
|
||||
assertNotNull(shared.getSerializationConfig().getDefaultTyper(shared.constructType(Object.class)));
|
||||
assertNull(copied.getSerializationConfig().getDefaultTyper(copied.constructType(Object.class)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user