From 0367dd3fd3eb84b50a700e7bf116d2a24eb7205c Mon Sep 17 00:00:00 2001
From: kangwenjing <1138819403@qq.com>
Date: Thu, 26 Nov 2026 09:43:35 +0800
Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=9E=E7=8E=B0=E5=A2=9E=E9=87=8F?=
=?UTF-8?q?=E5=90=8C=E6=AD=A5=E8=87=AA=E5=8A=A8=E8=B7=B3=E9=97=B8=E5=86=B7?=
=?UTF-8?q?=E5=8D=B4=E6=8E=A2=E6=B5=8B=E6=9C=BA=E5=88=B6?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../service/IdpIncrementalSyncService.java | 88 ++++++++++++++++---
.../IdpIncrementalSyncServiceTest.java | 83 ++++++++++++++++-
2 files changed, 157 insertions(+), 14 deletions(-)
diff --git a/backend/src/main/java/com/unis/crm/service/IdpIncrementalSyncService.java b/backend/src/main/java/com/unis/crm/service/IdpIncrementalSyncService.java
index f32febbd..2381ce4c 100644
--- a/backend/src/main/java/com/unis/crm/service/IdpIncrementalSyncService.java
+++ b/backend/src/main/java/com/unis/crm/service/IdpIncrementalSyncService.java
@@ -6,12 +6,15 @@ import com.unis.crm.config.IdpProperties;
import com.unis.crm.service.IdpUserResolver.HubIdentity;
import com.unis.crm.service.IdpUserResolver.LocalUser;
import com.unis.crm.service.IdpUserResolver.Resolution;
+import java.time.Clock;
import java.time.Duration;
+import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
@@ -44,6 +47,8 @@ public class IdpIncrementalSyncService {
private static final String ENTITY_USER = "user";
private static final String ENTITY_ORGANIZATION = "organization";
private static final String ACTION_DELETE = "delete";
+ /** 跳闸后的探测冷却,与轮询间隔同口径;配置页改完下一轮即可缩短/拉长。 */
+ static final long AUTO_DISABLE_RETRY_COOLDOWN_MS = 60_000L;
/**
* 运行时配置:增量开关与单批上限不用重启就能改,但生效速度取决于从哪里改,
@@ -72,6 +77,9 @@ public class IdpIncrementalSyncService {
/** 连续失败计数;达到阈值自动关增量只留全量,跑成功后清零。 */
private final AtomicInteger consecutiveFailures = new AtomicInteger();
private final AtomicBoolean autoDisabledByFailures = new AtomicBoolean();
+ /** 跳闸后下一次探测的解锁时刻;只放行探测,不提前清掉自动关闭标记。 */
+ private final AtomicReference retryAfter = new AtomicReference<>();
+ private final Clock clock;
@Autowired
public IdpIncrementalSyncService(
@@ -83,15 +91,8 @@ public class IdpIncrementalSyncService {
JdbcTemplate jdbcTemplate,
NamedParameterJdbcTemplate namedJdbcTemplate,
ObjectMapper objectMapper) {
- this.runtime = runtime;
- this.idpProperties = runtime.properties();
- this.idpClient = idpClient;
- this.normalizer = normalizer;
- this.idpUserResolver = idpUserResolver;
- this.idpUserSyncService = idpUserSyncService;
- this.jdbcTemplate = jdbcTemplate;
- this.namedJdbcTemplate = namedJdbcTemplate;
- this.objectMapper = objectMapper;
+ this(runtime, idpClient, normalizer, idpUserResolver, idpUserSyncService,
+ jdbcTemplate, namedJdbcTemplate, objectMapper, Clock.systemDefaultZone());
}
/** 单测入口:没有 sys_param 可读,增量开关与单批上限只认 yml/代码默认。 */
@@ -108,14 +109,70 @@ public class IdpIncrementalSyncService {
jdbcTemplate, namedJdbcTemplate, objectMapper);
}
+ /** 单测入口:用可控时钟驱动跳闸后的冷却探测,不用 sleep。 */
+ IdpIncrementalSyncService(
+ IdpProperties idpProperties,
+ IdpClient idpClient,
+ IdpDirectoryNormalizer normalizer,
+ IdpUserResolver idpUserResolver,
+ IdpUserSyncService idpUserSyncService,
+ JdbcTemplate jdbcTemplate,
+ NamedParameterJdbcTemplate namedJdbcTemplate,
+ ObjectMapper objectMapper,
+ Clock clock) {
+ this(new IdpRuntimeConfig(idpProperties), idpClient, normalizer, idpUserResolver, idpUserSyncService,
+ jdbcTemplate, namedJdbcTemplate, objectMapper, clock);
+ }
+
+ IdpIncrementalSyncService(
+ IdpRuntimeConfig runtime,
+ IdpClient idpClient,
+ IdpDirectoryNormalizer normalizer,
+ IdpUserResolver idpUserResolver,
+ IdpUserSyncService idpUserSyncService,
+ JdbcTemplate jdbcTemplate,
+ NamedParameterJdbcTemplate namedJdbcTemplate,
+ ObjectMapper objectMapper,
+ Clock clock) {
+ this.runtime = runtime;
+ this.idpProperties = runtime.properties();
+ this.idpClient = idpClient;
+ this.normalizer = normalizer;
+ this.idpUserResolver = idpUserResolver;
+ this.idpUserSyncService = idpUserSyncService;
+ this.jdbcTemplate = jdbcTemplate;
+ this.namedJdbcTemplate = namedJdbcTemplate;
+ this.objectMapper = objectMapper;
+ this.clock = clock;
+ }
+
/** 定时任务入口:开关判断在调用方(IdpSyncScheduler)与本方法内各判一次,防手动绕过。 */
public Map scheduledIncrement() {
if (!runtime.enabled() || !runtime.incrementEnabled()) {
return Map.of("result", "SKIPPED", "reason", "开关关闭");
}
if (autoDisabledByFailures.get()) {
- return Map.of("result", "SKIPPED",
- "reason", "增量连续失败 " + consecutiveFailures.get() + " 次已自动关闭,本轮只靠每日全量");
+ Instant nextProbe = retryAfter.get();
+ Instant now = clock.instant();
+ if (nextProbe == null) {
+ long cooldownMs = IdpSyncSchedule.resolveIntervalMs(runtime.incrementIntervalMs(),
+ idpProperties.getIncrement().getIntervalMs());
+ nextProbe = now.plusMillis(cooldownMs);
+ if (!retryAfter.compareAndSet(null, nextProbe)) {
+ nextProbe = retryAfter.get();
+ }
+ }
+ if (now.isBefore(nextProbe)) {
+ return Map.of("result", "SKIPPED",
+ "reason", "增量连续失败 " + consecutiveFailures.get() + " 次已自动关闭,"
+ + "下次探测 " + nextProbe + ",本轮只靠每日全量");
+ }
+ // 到点后用 CAS 抢占这一轮探测权,确保并发调用里只有一个放出去;失败会重设窗口,成功会清掉熔断。
+ long cooldownMs = IdpSyncSchedule.resolveIntervalMs(runtime.incrementIntervalMs(),
+ idpProperties.getIncrement().getIntervalMs());
+ if (!retryAfter.compareAndSet(nextProbe, now.plusMillis(cooldownMs))) {
+ return Map.of("result", "SKIPPED", "reason", "另一个探测正在进行,本轮跳过");
+ }
}
return incrementNow();
}
@@ -540,11 +597,18 @@ public class IdpIncrementalSyncService {
private int registerFailure(Map detail) {
int failures = consecutiveFailures.incrementAndGet();
detail.put("consecutiveFailures", failures);
+ long cooldownMs = IdpSyncSchedule.resolveIntervalMs(runtime.incrementIntervalMs(),
+ idpProperties.getIncrement().getIntervalMs());
+ retryAfter.updateAndGet(previous -> {
+ Instant candidate = clock.instant().plusMillis(cooldownMs);
+ return previous == null || candidate.isAfter(previous) ? candidate : previous;
+ });
// 阈值现读(清单键 crm.idp.increment.max-consecutive-failures):改大阈值不必重启就能止住自动关闭。
if (failures >= Math.max(1, runtime.incrementMaxConsecutiveFailures())) {
autoDisabledByFailures.set(true);
detail.put("autoDisabled", true);
- log.error("Idp incremental sync auto-disabled after {} consecutive failures", failures);
+ log.error("Idp incremental sync auto-disabled after {} consecutive failures, retry after {} ms",
+ failures, cooldownMs);
}
return failures;
}
diff --git a/backend/src/test/java/com/unis/crm/service/IdpIncrementalSyncServiceTest.java b/backend/src/test/java/com/unis/crm/service/IdpIncrementalSyncServiceTest.java
index 41bb47ff..f0c6ccff 100644
--- a/backend/src/test/java/com/unis/crm/service/IdpIncrementalSyncServiceTest.java
+++ b/backend/src/test/java/com/unis/crm/service/IdpIncrementalSyncServiceTest.java
@@ -313,8 +313,11 @@ class IdpIncrementalSyncServiceTest {
assertEquals(Boolean.TRUE, ((Map, ?>) third.get("detail")).get("autoDisabled"));
assertTrue(service.isAutoDisabledByFailures(),
"键名被改时每轮都失败,必须计入连续失败并在 3 轮后自动关增量(契约 4),不然它永远「看起来正常」");
- assertEquals("SKIPPED", service.scheduledIncrement().get("result"),
- "自动关掉之后定时入口要直接跳过,只靠每日全量兜");
+ Map skipped = service.scheduledIncrement();
+ assertEquals("SKIPPED", skipped.get("result"),
+ "跳闸后冷却期内定时入口要跳过,不能每轮都打 Hub");
+ assertTrue(String.valueOf(skipped.get("reason")).contains("下次探测"),
+ "跳过原因要告诉运维冷却到什么时候: " + skipped);
}
/**
@@ -561,6 +564,82 @@ class IdpIncrementalSyncServiceTest {
assertTrue(service.isAutoDisabledByFailures(), "连续 3 次失败要自动关增量(契约 4)");
}
+ /** 跳闸后不能靠重启恢复:冷却结束必须自动放行一次真实探测,成功后清掉熔断。 */
+ @Test
+ void autoDisabled_recoversOnFirstSuccessfulProbeAfterCooldown() throws Exception {
+ MutableClock clock = new MutableClock();
+ properties.getIncrement().setIntervalMs(IdpIncrementalSyncService.AUTO_DISABLE_RETRY_COOLDOWN_MS);
+ service = new IdpIncrementalSyncService(properties, idpClient, new IdpDirectoryNormalizer(properties, MAPPER),
+ resolver, syncService, jdbcTemplate, namedJdbcTemplate, MAPPER, clock);
+ IdpClient.HubResponse goodPage = new IdpClient.HubResponse(200, fixture("changes-page.json"));
+ IdpClient.HubResponse emptyPage = new IdpClient.HubResponse(200, fixture("changes-page-empty.json"));
+ when(idpClient.fetchChanges(anyLong(), anyInt()))
+ .thenThrow(new IdpClient.IdpCallException(IdpClient.CODE_IDP_UNAVAILABLE, "不可达", 0))
+ .thenThrow(new IdpClient.IdpCallException(IdpClient.CODE_IDP_UNAVAILABLE, "不可达", 0))
+ .thenThrow(new IdpClient.IdpCallException(IdpClient.CODE_IDP_UNAVAILABLE, "不可达", 0))
+ .thenReturn(goodPage, emptyPage);
+ for (int round = 1; round <= 3; round++) {
+ assertEquals("FAILED", service.incrementNow().get("result"));
+ }
+ assertTrue(service.isAutoDisabledByFailures());
+
+ clearInvocations(idpClient);
+ assertEquals("SKIPPED", service.scheduledIncrement().get("result"), "冷却期内不许探测");
+ verify(idpClient, never()).fetchChanges(anyLong(), anyInt());
+
+ clock.advanceMillis(IdpIncrementalSyncService.AUTO_DISABLE_RETRY_COOLDOWN_MS + 1);
+ Map probe = service.scheduledIncrement();
+ assertEquals("SUCCESS", probe.get("result"), "冷却结束应自动探测并成功,不再需要重启");
+ verify(idpClient, atLeastOnce()).fetchChanges(anyLong(), anyInt());
+ assertFalse(service.isAutoDisabledByFailures(), "探测成功后熔断必须复位");
+ }
+
+ /** 探测仍失败时重新进入冷却,不能每轮都拿 Hub 当靶子打。 */
+ @Test
+ void autoDisabled_restartsCooldownWhenProbeStillFails() {
+ MutableClock clock = new MutableClock();
+ properties.getIncrement().setIntervalMs(IdpIncrementalSyncService.AUTO_DISABLE_RETRY_COOLDOWN_MS);
+ service = new IdpIncrementalSyncService(properties, idpClient, new IdpDirectoryNormalizer(properties, MAPPER),
+ resolver, syncService, jdbcTemplate, namedJdbcTemplate, MAPPER, clock);
+ when(idpClient.fetchChanges(anyLong(), anyInt()))
+ .thenThrow(new IdpClient.IdpCallException(IdpClient.CODE_IDP_UNAVAILABLE, "不可达", 0));
+ for (int round = 1; round <= 3; round++) {
+ assertEquals("FAILED", service.incrementNow().get("result"));
+ }
+ clearInvocations(idpClient);
+
+ clock.advanceMillis(IdpIncrementalSyncService.AUTO_DISABLE_RETRY_COOLDOWN_MS + 1);
+ assertEquals("FAILED", service.scheduledIncrement().get("result"), "冷却结束后应探测一次");
+ verify(idpClient, times(1)).fetchChanges(anyLong(), anyInt());
+ assertEquals("SKIPPED", service.scheduledIncrement().get("result"), "探测失败后要重新冷却");
+ verify(idpClient, times(1)).fetchChanges(anyLong(), anyInt());
+ assertTrue(service.isAutoDisabledByFailures());
+ }
+
+ /** 测试时钟:只往前走,避免依赖真实 sleep 或挂钟。 */
+ private static final class MutableClock extends java.time.Clock {
+ private java.time.Instant now = java.time.Instant.parse("2026-11-26T00:00:00Z");
+
+ @Override
+ public java.time.ZoneId getZone() {
+ return java.time.ZoneOffset.UTC;
+ }
+
+ @Override
+ public java.time.Clock withZone(java.time.ZoneId zone) {
+ return this;
+ }
+
+ @Override
+ public java.time.Instant instant() {
+ return now;
+ }
+
+ void advanceMillis(long millis) {
+ now = now.plusMillis(millis);
+ }
+ }
+
@SuppressWarnings("unchecked")
private static Map castDetail(Map summary) {
Object detail = summary.get("detail");