From 8dc742f2585f65e3bbb8bbf21e400b695da992a9 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:44:14 +0800 Subject: [PATCH 1/5] fix: restore legacy counters in native Ehcache 3 --- README.md | 2 + README.zh-CN.md | 2 + .../ehcache/Ehcache3CredentialRetryStore.java | 21 +++++++ ...e3CredentialRetryStoreIntegrationTest.java | 56 +++++++++++++++++++ 4 files changed, 81 insertions(+) diff --git a/README.md b/README.md index 7d860a6..259fa78 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,8 @@ For an existing Ehcache 2 retry cache, stop all legacy clients of that region be For native Ehcache 3, pause all retry clients, drain writes, and use exactly one migration writer per region. Call `migrateLegacyWindow` for each known principal using the original cache. The region must use creation-only or eternal expiry. A region that accepts both legacy counters and retry windows, such as `Serializable`, stores attempts directly. An `AtomicInteger`-typed region stores a serializable counter subtype holding the window ID and must preserve that subtype. Live entries are replaced in place while retaining the existing deadline. A policy that resets expiry on writes requires a separate cutover. +For rollback, keep retry clients paused and drain outstanding writes before calling `restoreLegacyWindow` for each known principal. The cache must accept `AtomicInteger`. A live retry window becomes a plain legacy counter with its current count and original deadline. Missing, expired, and already restored entries are skipped. + For Hazelcast 5.2+ and 3.12, use the same cutover steps for the dedicated retry IMap. Deploy the retry-store module to every member and reuse the original map and principal keys. The first reservation converts the legacy counter atomically, retaining its remaining TTL and refreshing idle time under the existing policy. For the 3.12 adapter, supply the map's configured max idle explicitly. For an existing JCache retry region, stop legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. A region that accepts both value types, for example with value type `Object`, stores retry windows directly. A region typed as `AtomicInteger` stores a serializable counter subtype holding the window ID. Verify that the provider and its configured serializer retain the subtype and deploy this module to every executing member before cutover. Typed migration was verified on a two-member Hazelcast JCache cluster. For rollback, pause all retry clients, drain outstanding writes, and call `restoreLegacyWindow` for every converted principal in the original region. It restores a plain `AtomicInteger` with the current count and original deadline. It skips missing, expired, and restored entries. Check for any remaining converted entries before resuming legacy clients. diff --git a/README.zh-CN.md b/README.zh-CN.md index 9ad552c..627275e 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -203,6 +203,8 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); 对于原生 Ehcache 3,暂停所有重试客户端并排空在途写入,每个区域只允许一个迁移写入方。使用原缓存对已知主体调用 `migrateLegacyWindow`。区域须使用仅在创建时设置的过期策略或永不过期策略。`Serializable` 等可接受旧计数和新窗口的区域直接保存新窗口。`AtomicInteger` 类型区域保存含窗口 ID 的可序列化子类型,要求序列化器保留该类型。活跃条目在原位置替换,保留原截止时间。会在写入时重置截止时间的策略需要独立切换方案。 +回滚时保持客户端暂停并排空在途写入,再对已知主体调用 `restoreLegacyWindow`。缓存区域必须接受 `AtomicInteger`。活跃窗口恢复为普通旧版计数,保留当前次数和原截止时间。缺失、已过期或已经恢复的条目会跳过。 + Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所有集群成员须部署重试存储模块,并沿用原 IMap 和主体键。首次预留会原子转换旧计数,保留剩余 TTL,并按原策略刷新空闲时间。使用 3.12 适配器时需传入 IMap 配置的最大空闲时长。 对于现有 JCache 重试区域,停止旧客户端后沿用原区域和主体键。条目处理器会在同一次更新中转换计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留原截止时间。值类型允许两种格式的区域(例如 `Object`)直接存储重试窗口。值类型为 `AtomicInteger` 的区域使用可序列化的计数器子类保存窗口标识。切换前验证提供方及其序列化配置能保留子类,并在所有执行节点部署此模块。该类型区域的迁移已在双节点 Hazelcast JCache 集群验证。回切时暂停所有重试客户端,等待在途写入完成,然后对原区域内每个已转换的主体调用 `restoreLegacyWindow`。该方法原地恢复普通 `AtomicInteger`,保留当前计数和原截止时间,跳过缺失、过期或已恢复条目。检查区域中是否仍有已转换条目,再恢复旧客户端。 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java index 9300184..e210573 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java @@ -135,6 +135,27 @@ public boolean migrateLegacyWindow(Object principal) { return Objects.nonNull(cache.replace(key, migrated)); } + /** + * Converts a live retry window back to a legacy counter while retaining its expiry. + * Pause all retry clients and drain outstanding writes before restoring the region. + * + * @param principal original principal in the Ehcache region + * @return true when a live retry window was restored + */ + public boolean restoreLegacyWindow(Object principal) { + if (!cache.getRuntimeConfiguration().getValueType().isAssignableFrom(AtomicInteger.class)) { + throw new IllegalArgumentException("Ehcache retry region must accept legacy counters"); + } + K key = key(principal); + Object value = cache.get(key); + Attempt attempt = storedAttempt(value); + if (Objects.isNull(attempt) && !isMigratedZero(value)) { + return false; + } + int count = Objects.nonNull(attempt) ? attempt.getCount() : 0; + return cache.replace(key, value, new AtomicInteger(count)); + } + private Object storeValue(Attempt attempt) { return usesTypedCounters ? new TypedCounter(attempt.getWindowId(), attempt.getCount()) : attempt; } diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java index 41c0de8..ef56076 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java @@ -177,6 +177,62 @@ public void migratesAndReservesSerializedCountersInAnAtomicIntegerRegion() throw } } + @Test + public void restoresLegacyCountersWithoutRestartingTheDeadline() { + assertLegacyRestore(Serializable.class); + assertLegacyRestore(AtomicInteger.class); + } + + private void assertLegacyRestore(Class valueType) { + AtomicLong time = new AtomicLong(10_000); + try (CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder() + .using(new TimeSourceConfiguration(time::get)) + .withCache("legacy", CacheConfigurationBuilder.newCacheConfigurationBuilder( + String.class, valueType, + ResourcePoolsBuilder.newResourcePoolsBuilder().offheap(2, MemoryUnit.MB)) + .withExpiry(Ehcache3CredentialRetryStore.fixedWindowExpiry(Duration.ofSeconds(3)))) + .build(true)) { + Cache cache = manager.getCache("legacy", String.class, valueType); + cache.put("alice", valueType.cast(new AtomicInteger(3))); + cache.put("zero", valueType.cast(new AtomicInteger(0))); + cache.put("untouched", valueType.cast(new AtomicInteger(5))); + Ehcache3CredentialRetryStore store = new Ehcache3CredentialRetryStore<>(cache, Object::toString); + assertTrue(store.migrateLegacyWindow("alice")); + assertTrue(store.migrateLegacyWindow("zero")); + Attempt attempt = store.reserve("alice"); + time.set(12_000); + + assertTrue(store.restoreLegacyWindow("alice")); + assertTrue(store.restoreLegacyWindow("zero")); + assertFalse(store.restoreLegacyWindow("missing")); + assertFalse(store.restoreLegacyWindow("alice")); + assertFalse(store.restoreLegacyWindow("untouched")); + store.clearIfCurrent("alice", attempt.getWindowId()); + + assertEquals(AtomicInteger.class, cache.get("alice").getClass()); + assertEquals(4, ((AtomicInteger) cache.get("alice")).get()); + assertEquals(AtomicInteger.class, cache.get("zero").getClass()); + assertEquals(0, ((AtomicInteger) cache.get("zero")).get()); + assertEquals(5, ((AtomicInteger) cache.get("untouched")).get()); + time.set(13_001); + assertNull(cache.get("alice")); + assertNull(cache.get("zero")); + assertFalse(store.restoreLegacyWindow("alice")); + } + } + + @Test + public void rejectsLegacyRestoreWhenTheRegionAcceptsOnlyAttempts() { + try (CacheManager manager = manager(new AtomicLong(10_000), + Ehcache3CredentialRetryStore.fixedWindowExpiry(Duration.ofSeconds(3)))) { + Cache cache = manager.getCache("retry", String.class, Attempt.class); + Ehcache3CredentialRetryStore store = new Ehcache3CredentialRetryStore<>(cache, Object::toString); + Attempt original = store.reserve("alice"); + assertThrows(IllegalArgumentException.class, () -> store.restoreLegacyWindow("alice")); + assertEquals(original, cache.get("alice")); + } + } + @Test public void rejectsPoliciesThatReplaceExpiryOnWrites() { try (CacheManager manager = manager(new AtomicLong(10_000), From 25f0d8cff41252a0d4ede4b13b2c86ec9c368182 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:52:12 +0800 Subject: [PATCH 2/5] test: let Hazelcast integration members bind ephemeral ports --- ...stCredentialRetryStoreIntegrationTest.java | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java index 3e8d9b7..ceb43f2 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java @@ -7,9 +7,6 @@ import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.map.IMap; -import java.io.IOException; -import java.net.InetAddress; -import java.net.ServerSocket; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -37,18 +34,22 @@ public class HazelcastCredentialRetryStoreIntegrationTest { private static HazelcastInstance second; @BeforeClass - public static void startCluster() throws IOException { + public static void startCluster() { String cluster = "shiro-map-" + UUID.randomUUID(); - int firstPort; - int secondPort; - try (ServerSocket a = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1")); - ServerSocket b = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { - firstPort = a.getLocalPort(); - secondPort = b.getLocalPort(); - } - first = Hazelcast.newHazelcastInstance(member(cluster, firstPort, secondPort)); - second = Hazelcast.newHazelcastInstance(member(cluster, secondPort, firstPort)); + first = Hazelcast.newHazelcastInstance(member(cluster)); + int firstPort = first.getCluster().getLocalMember().getAddress().getPort(); + + Config joiningMember = member(cluster); + joiningMember.getNetworkConfig().getJoin().getTcpIpConfig() + .addMember("127.0.0.1:" + firstPort); + second = Hazelcast.newHazelcastInstance(joiningMember); + int secondPort = second.getCluster().getLocalMember().getAddress().getPort(); + + assertTrue(firstPort > 0); + assertTrue(secondPort > 0); + assertNotEquals(firstPort, secondPort); assertEquals(2, first.getCluster().getMembers().size()); + assertEquals(2, second.getCluster().getMembers().size()); } @AfterClass @@ -171,7 +172,7 @@ private static void awaitDeadline(long deadline) throws InterruptedException { } } - private static Config member(String cluster, int ownPort, int otherPort) { + private static Config member(String cluster) { Config config = new Config().setClusterName(cluster); config.setProperty("hazelcast.logging.type", "none"); config.setProperty("hazelcast.operation.thread.count", "2"); @@ -183,11 +184,11 @@ private static Config member(String cluster, int ownPort, int otherPort) { config.addMapConfig(new MapConfig("ttl").setTimeToLiveSeconds(3).setMaxIdleSeconds(10)); config.addMapConfig(new MapConfig("idle").setMaxIdleSeconds(2)); NetworkConfig network = config.getNetworkConfig(); - network.setPort(ownPort).setPortAutoIncrement(false); + network.setPort(0).setPortAutoIncrement(false); network.getInterfaces().setEnabled(true).addInterface("127.0.0.1"); network.getJoin().getAutoDetectionConfig().setEnabled(false); network.getJoin().getMulticastConfig().setEnabled(false); - network.getJoin().getTcpIpConfig().setEnabled(true).addMember("127.0.0.1:" + otherPort); + network.getJoin().getTcpIpConfig().setEnabled(true); return config; } } From 290eced1511fb3a3fcb01ea77c847d10dd203511 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:03:53 +0800 Subject: [PATCH 3/5] Verify bounded cutover for renewing Ehcache retry regions --- README.md | 4 +- README.zh-CN.md | 4 +- ...e3CredentialRetryStoreIntegrationTest.java | 40 +++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 259fa78..4171407 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,9 @@ For a Spring-managed retry matcher with cache name `login`, declare a provider-b For an existing Ehcache 2 retry cache, stop all legacy clients of that region before enabling the shared store. Reuse the same region and principal keys. The first reservation upgrades the stored legacy counter under the key lock, counts the current attempt and keeps the original TTL deadline and the configured time-to-idle policy. Use a strongly consistent region when clustered. -For native Ehcache 3, pause all retry clients, drain writes, and use exactly one migration writer per region. Call `migrateLegacyWindow` for each known principal using the original cache. The region must use creation-only or eternal expiry. A region that accepts both legacy counters and retry windows, such as `Serializable`, stores attempts directly. An `AtomicInteger`-typed region stores a serializable counter subtype holding the window ID and must preserve that subtype. Live entries are replaced in place while retaining the existing deadline. A policy that resets expiry on writes requires a separate cutover. +For native Ehcache 3, pause all retry clients, drain writes, and use exactly one migration writer per region. Call `migrateLegacyWindow` for each known principal using the original cache. The region must use creation-only or eternal expiry. A region that accepts both legacy counters and retry windows, such as `Serializable`, stores attempts directly. An `AtomicInteger`-typed region stores a serializable counter subtype holding the window ID and must preserve that subtype. Live entries are replaced in place while retaining the existing deadline. + +For legacy regions using a verified finite TTL or TTI that renews on updates or reads, use a bounded drain for cutover. Pause all clients and background jobs that can access the retry region, and wait until in-flight operations finish. From that point, wait at least the longest configured lifetime across the source regions, including any clock margin required by the deployment. Enable the new store on a separate region only after that interval, with its configured creation window. The old region is left intact and its counters expire on their own. This path requires a maintenance pause and explicit acceptance of the new region’s fixed-window policy. Eternal entries, custom policies with unknown upper bounds, and deployments that must retain renewal behavior require a different path. For rollback, keep retry clients paused and drain outstanding writes before calling `restoreLegacyWindow` for each known principal. The cache must accept `AtomicInteger`. A live retry window becomes a plain legacy counter with its current count and original deadline. Missing, expired, and already restored entries are skipped. diff --git a/README.zh-CN.md b/README.zh-CN.md index 627275e..05201ca 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -201,7 +201,9 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); 对于现有 Ehcache 2 重试缓存,先停止访问该区域的全部旧版客户端,再启用共享重试存储,并沿用原区域及主体键。首次预留在键锁内转换已保存的旧计数,计入本次尝试,并保留原 TTL 截止时间和配置的空闲过期策略。集群部署使用强一致性区域。 -对于原生 Ehcache 3,暂停所有重试客户端并排空在途写入,每个区域只允许一个迁移写入方。使用原缓存对已知主体调用 `migrateLegacyWindow`。区域须使用仅在创建时设置的过期策略或永不过期策略。`Serializable` 等可接受旧计数和新窗口的区域直接保存新窗口。`AtomicInteger` 类型区域保存含窗口 ID 的可序列化子类型,要求序列化器保留该类型。活跃条目在原位置替换,保留原截止时间。会在写入时重置截止时间的策略需要独立切换方案。 +对于原生 Ehcache 3,暂停所有重试客户端并排空在途写入,每个区域只允许一个迁移写入方。使用原缓存对已知主体调用 `migrateLegacyWindow`。区域须使用仅在创建时设置的过期策略或永不过期策略。`Serializable` 等可接受旧计数和新窗口的区域直接保存新窗口。`AtomicInteger` 类型区域保存含窗口 ID 的可序列化子类型,要求序列化器保留该类型。活跃条目在原位置替换,保留原截止时间。 + +旧区域的 TTL 或 TTI 若会因写入或访问续期,且能确认有限上界,可在维护窗口内排空切换。暂停所有可能访问旧重试区域的客户端和后台任务,等在途操作全部完成。从该时点起,至少等待所有来源区域配置中最长的一段有效期,并计入部署所需的时钟余量。等待结束后,在独立区域启用新存储并配置创建窗口。旧区域保持原状,已有计数按自身策略自然到期。该路径需要维护停顿,并确认新区域采用固定窗口。存在永不过期条目、无法证明上界的自定义策略,或必须继续保留续期行为时,需另选切换方式。 回滚时保持客户端暂停并排空在途写入,再对已知主体调用 `restoreLegacyWindow`。缓存区域必须接受 `AtomicInteger`。活跃窗口恢复为普通旧版计数,保留当前次数和原截止时间。缺失、已过期或已经恢复的条目会跳过。 diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java index ef56076..e2e5bb8 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java @@ -243,6 +243,46 @@ public void rejectsPoliciesThatReplaceExpiryOnWrites() { } } + @Test + public void drainsFiniteRenewingLegacyWindowsBeforeStartingTheNewRegion() { + AtomicLong time = new AtomicLong(10_000); + Duration window = Duration.ofSeconds(5); + try (CacheManager manager = manager(time, Ehcache3CredentialRetryStore.fixedWindowExpiry(window))) { + Cache ttl = manager.createCache("legacy-ttl", + CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, AtomicInteger.class, + ResourcePoolsBuilder.newResourcePoolsBuilder().offheap(2, MemoryUnit.MB)) + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(window))); + Cache idle = manager.createCache("legacy-idle", + CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, AtomicInteger.class, + ResourcePoolsBuilder.newResourcePoolsBuilder().offheap(2, MemoryUnit.MB)) + .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(window))); + ttl.put("alice", new AtomicInteger(2)); + idle.put("alice", new AtomicInteger(4)); + + time.set(12_000); + ttl.put("alice", new AtomicInteger(3)); + assertEquals(4, idle.get("alice").get()); + + time.set(15_001); + assertEquals(3, ttl.get("alice").get()); + assertEquals(4, idle.get("alice").get()); + + // The last idle read and the last TTL write are now both behind the drain bound. + time.set(20_002); + assertNull(ttl.get("alice")); + assertNull(idle.get("alice")); + + Cache destination = manager.getCache("retry", String.class, Attempt.class); + Ehcache3CredentialRetryStore store = new Ehcache3CredentialRetryStore<>( + destination, Object::toString); + assertEquals(1, store.reserve("alice").getCount()); + time.set(25_001); + assertEquals(2, store.reserve("alice").getCount()); + time.set(25_003); + assertNull(destination.get("alice")); + } + } + private static CacheManager manager(AtomicLong time, ExpiryPolicy policy) { return CacheManagerBuilder.newCacheManagerBuilder() .using(new TimeSourceConfiguration(time::get)) From bf14f91e247898d5eadd008a9a37d53867f252f7 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:34:10 +0800 Subject: [PATCH 4/5] fix: import verified Memcached retry expiry snapshots Refs #6 --- .github/workflows/ci.yml | 1 + README.md | 2 + README.zh-CN.md | 2 + .../J2CacheMemcachedCredentialRetryStore.java | 18 +++++++++ ...edCredentialRetryStoreIntegrationTest.java | 38 ++++++++++++++++++- 5 files changed, 60 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5a38afd..af3ca95 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -138,6 +138,7 @@ jobs: for name in ( "importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline", "refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter", + "importsAuthoritativeSnapshotWithTheOriginalServerDeadline", "importsLegacyWindowsAfterBinarySourceWarmRestart", ): case = suite.find(f'./testcase[@name="{name}"]') diff --git a/README.md b/README.md index 4171407..bd3c71a 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,8 @@ The J2Cache Jedis and Lettuce adapters also expose `migrateLegacyWindow` for eac The J2Cache Memcached adapter can import a known principal during the same exclusive cutover. Select the source server using the original key routing. On a trusted source that accepts the Meta Text protocol, pass its address to `migrateLegacyWindow`. For authenticated access, first authenticate a dedicated Meta Text connection, configure a finite socket read timeout, and pass it to `migrateLegacyWindowFromMetaConnection`. The caller manages authentication, transport security, and closure of that connection. It must have no outstanding commands and be used by one reader at a time. The adapter reads the value with its remaining TTL, determines the absolute deadline at server-second precision, retains the original entry, and creates the destination only if it is absent. A binary-only source, including one that requires binary SASL, requires a separate migration path because its get operation does not report the existing TTL. For windows with a verified finite TTL bound, pause and drain all retry clients, then wait for the maximum remaining lifetime across the source nodes before enabling the new store. For persistent windows or unknown TTL bounds, keep using the legacy store until you can obtain an authoritative expiry snapshot. Binary GET returns the counter and CAS, which cannot distinguish a finite window from a persistent one. +During the exclusive cutover, pass a verified count and its original absolute Unix deadline from the same source entry to `migrateLegacyWindowFromSnapshot`. Use zero only for a confirmed persistent entry. Import while clients are paused and writes are drained. Expired snapshots and attempts to overwrite existing destination windows return false. + If the binary-only source already runs with [Memcached warm restart](https://docs.memcached.org/features/restart/) enabled on a retained RAM-backed memory file, it can expose the restored windows to the existing Meta Text importer during the exclusive cutover. Keep clients paused and writes drained. Gracefully stop the source with `SIGUSR1`, wait until the host clock advances beyond the saved stop second, and restart it from the same memory file with compatible slab and CAS settings and an isolated Meta Text listener. Keep the listener authenticated or restricted to trusted local access. Verify that the source actually recovered its items before importing. A loopback Memcached 1.6.45 fixture restored a finite window with its exact original deadline and restored a persistent window with no deadline. A third window that expired during the restart stayed absent. This route requires warm restart to have been enabled before the legacy windows were written. For a retry cache stored in a Redisson 3.12.5 `RMapCache`, pass the original cache and principal to `migrateLegacyWindow` during the same exclusive cutover. The adapter copies the count, entry lifetime, idle policy and current idle deadline without refreshing the source. It also honors a shorter map-wide expiry. Use a distinct destination namespace on the same Redis deployment. diff --git a/README.zh-CN.md b/README.zh-CN.md index 05201ca..49d44ed 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -217,6 +217,8 @@ J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字 J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由选择保存旧值的源节点。对允许 Meta Text 协议的可信源节点,可向 `migrateLegacyWindow` 传入地址。需要认证时,先认证专用 Meta Text 连接,设置有限的读取超时,再传给 `migrateLegacyWindowFromMetaConnection`。调用方负责认证、传输安全和关闭连接。连接上应没有在途命令,并由单个调用方顺序读取。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议的节点(包括要求二进制 SASL 的节点)仍需要独立迁移方式,因为其 GET 操作不返回原有效期。 如果能确认所有旧窗口的有效期上限,先暂停旧、新客户端并排空在途写入,等待所有源节点上的旧窗口过期,再启用新存储。存在永久窗口或无法确认有效期上限时,应继续使用旧存储,直到取得可信的到期时间快照。二进制 GET 返回计数和 CAS,无法区分限时窗口和永久窗口。 +独占切换期间可调用 `migrateLegacyWindowFromSnapshot`。先暂停重试客户端并排空在途写入,再传入同一源条目的可信计数和原始 Unix 秒截止时间。只有已确认永久有效的条目才传 0。已过期或目标窗口已存在时返回 false。 + 如果仅支持二进制协议的源节点已在可保留的内存文件上启用 [Memcached 热重启](https://docs.memcached.org/features/restart/),可在独占切换期间通过现有 Meta Text 导入器读取恢复后的窗口。保持客户端暂停并排空在途写入。向源进程发送 `SIGUSR1` 以正常停机,等待主机时钟超过记录的停机秒数,再使用同一个内存文件和兼容的 slab、CAS 设置重启,并开放隔离的 Meta Text 监听。监听应启用认证或限制为可信本机访问。确认源条目确实恢复后再导入。Memcached 1.6.45 回环测试保留了限时窗口的原始截止时间和永久窗口的无截止状态,停机期间已过期的窗口也未恢复。此方式要求在写入旧窗口前已启用热重启。 对于 Redisson 3.12.5 的 `RMapCache` 重试区域,在同一独占切换阶段使用原缓存和主体调用 `migrateLegacyWindow`。导入复制原计数、条目固定截止时间、空闲策略和当前空闲截止时间,读取时不延长源窗口。若整个 Map 更早过期,使用更早的截止时间。同一 Redis 部署内使用独立的目标命名空间。 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java index 0e0f323..249fdcc 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java @@ -160,6 +160,24 @@ public boolean migrateLegacyWindowFromMetaConnection(String principal, Socket so }); } + /** + * Imports a verified legacy counter and its original deadline during an exclusive cutover. + * Pause retry clients and drain outstanding writes before taking the snapshot. Supply the + * count and deadline from the same source entry and use zero only for a persistent entry. + * + * @param principal original string principal in the J2Cache region + * @param count original nonnegative retry count + * @param deadlineEpochSecond original absolute expiry, or zero for a persistent entry + * @return true when an active snapshot was copied to an empty destination + */ + public boolean migrateLegacyWindowFromSnapshot(String principal, int count, long deadlineEpochSecond) { + if (count < 0 || deadlineEpochSecond < 0 || deadlineEpochSecond > Integer.MAX_VALUE) { + throw new IllegalArgumentException("Invalid Memcached snapshot retry count or expiry"); + } + MemcachedLegacyWindow legacy = new MemcachedLegacyWindow(count, (int) deadlineEpochSecond); + return migrateLegacyWindow(principal, ignored -> legacy); + } + private boolean migrateLegacyWindow(String principal, LegacyRead source) { Objects.requireNonNull(principal, "principal"); try { diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java index 3561a42..fb083c5 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java @@ -203,10 +203,11 @@ public void refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter() throws E String legacyKey = REGION + ":" + principal; String target = "shiro-retry:" + digest(namespace) + ":" + digest(principal); SerializingTranscoder transcoder = new SerializingTranscoder(); + int sourceDeadline = Math.toIntExact(Instant.now().getEpochSecond() + 120); byte[] counter = SerializationUtils.serialize(new AtomicInteger(3)); MemcachedClient legacy = client(binaryEndpoint); try (CacheChannel channel = J2CacheTestChannel.open(config)) { - assertTrue(legacy.set(legacyKey, 120, counter, transcoder)); + assertTrue(legacy.set(legacyKey, sourceDeadline, counter, transcoder)); byte[] storedCounter = (byte[]) legacy.get(legacyKey, transcoder); assertEquals(3, ((AtomicInteger) SerializationUtils.deserialize(storedCounter)).get()); long originalCas = legacy.gets(legacyKey, transcoder).getCas(); @@ -215,12 +216,47 @@ public void refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter() throws E assertThrows(CacheException.class, () -> store.migrateLegacyWindow(principal, AddrUtil.getOneAddress(binaryEndpoint))); assertNull(firstClient.get(target, new StringTranscoder())); + assertTrue(store.migrateLegacyWindowFromSnapshot(principal, 3, sourceDeadline)); + assertEquals(4, store.reserve(principal).getCount()); assertEquals(originalCas, legacy.gets(legacyKey, transcoder).getCas()); } finally { legacy.shutdown(); } } + @Test + public void importsAuthoritativeSnapshotWithTheOriginalServerDeadline() throws Exception { + J2CacheConfig config = config(true, "30s"); + try (CacheChannel channel = J2CacheTestChannel.open(config)) { + J2CacheMemcachedCredentialRetryStore store = store(channel, config, firstClient); + String principal = "snapshot-" + UUID.randomUUID(); + String persistent = principal + "-persistent"; + String expired = principal + "-expired"; + int deadline = Math.toIntExact(Instant.now().getEpochSecond() + 90); + assertThrows(IllegalArgumentException.class, + () -> store.migrateLegacyWindowFromSnapshot(principal, -1, deadline)); + assertThrows(IllegalArgumentException.class, + () -> store.migrateLegacyWindowFromSnapshot(principal, 3, -1)); + assertThrows(IllegalArgumentException.class, + () -> store.migrateLegacyWindowFromSnapshot(principal, 3, Integer.MAX_VALUE + 1L)); + assertTrue(store.migrateLegacyWindowFromSnapshot(principal, 3, deadline)); + assertFalse(store.migrateLegacyWindowFromSnapshot(principal, 6, deadline + 5L)); + assertTrue(store.migrateLegacyWindowFromSnapshot(persistent, 0, 0)); + assertFalse(store.migrateLegacyWindowFromSnapshot(expired, 7, deadline - 91L)); + assertNull(firstClient.get("shiro-retry:" + digest(namespace) + ":" + digest(expired), + new StringTranscoder())); + + Attempt next = store.reserve(principal); + Attempt persistentAttempt = store.reserve(persistent); + assertEquals(4, next.getCount()); + assertEquals(1, persistentAttempt.getCount()); + String target = "shiro-retry:" + digest(namespace) + ":" + digest(principal); + String persistentKey = "shiro-retry:" + digest(namespace) + ":" + digest(persistent); + assertEquals(deadline + ":4:" + next.getWindowId(), firstClient.get(target, new StringTranscoder())); + assertStoredDeadlines(target, deadline, persistentKey); + } + } + @Test public void importsLegacyWindowsAfterBinarySourceWarmRestart() throws Exception { String sourcePort = System.getProperty("shiro.memcached.warm.test.port"); From bd36866b033703ea30af49ab5a310186a7bbfb23 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:03:56 +0800 Subject: [PATCH 5/5] fix: bind Memcached retry snapshot to the source entry version --- README.md | 2 ++ README.zh-CN.md | 2 ++ .../J2CacheMemcachedCredentialRetryStore.java | 34 +++++++++++++++++-- .../cache/j2cache/MemcachedLegacyWindow.java | 22 ++++++++++-- ...edCredentialRetryStoreIntegrationTest.java | 20 +++++++++-- 5 files changed, 72 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index bd3c71a..5ee950f 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,8 @@ The J2Cache Memcached adapter can import a known principal during the same exclu During the exclusive cutover, pass a verified count and its original absolute Unix deadline from the same source entry to `migrateLegacyWindowFromSnapshot`. Use zero only for a confirmed persistent entry. Import while clients are paused and writes are drained. Expired snapshots and attempts to overwrite existing destination windows return false. +During the same exclusive cutover, the overload of `migrateLegacyWindowFromSnapshot` that accepts a source client and a nonzero CAS also checks the live entry version and decoded count. It returns false if the source is missing, the version or count changed, the deadline passed, or the destination already has a window. The caller must connect to the original source process with the same routing and record the CAS, count and authoritative deadline together. The binary protocol provides the entry version and value. The deadline still comes from the trusted snapshot. + If the binary-only source already runs with [Memcached warm restart](https://docs.memcached.org/features/restart/) enabled on a retained RAM-backed memory file, it can expose the restored windows to the existing Meta Text importer during the exclusive cutover. Keep clients paused and writes drained. Gracefully stop the source with `SIGUSR1`, wait until the host clock advances beyond the saved stop second, and restart it from the same memory file with compatible slab and CAS settings and an isolated Meta Text listener. Keep the listener authenticated or restricted to trusted local access. Verify that the source actually recovered its items before importing. A loopback Memcached 1.6.45 fixture restored a finite window with its exact original deadline and restored a persistent window with no deadline. A third window that expired during the restart stayed absent. This route requires warm restart to have been enabled before the legacy windows were written. For a retry cache stored in a Redisson 3.12.5 `RMapCache`, pass the original cache and principal to `migrateLegacyWindow` during the same exclusive cutover. The adapter copies the count, entry lifetime, idle policy and current idle deadline without refreshing the source. It also honors a shorter map-wide expiry. Use a distinct destination namespace on the same Redis deployment. diff --git a/README.zh-CN.md b/README.zh-CN.md index 49d44ed..23fd807 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -219,6 +219,8 @@ J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体 独占切换期间可调用 `migrateLegacyWindowFromSnapshot`。先暂停重试客户端并排空在途写入,再传入同一源条目的可信计数和原始 Unix 秒截止时间。只有已确认永久有效的条目才传 0。已过期或目标窗口已存在时返回 false。 +独占切换期间也可使用接收源客户端和非零 CAS 的 `migrateLegacyWindowFromSnapshot` 重载。它会核对源条目当前的版本和解码后的计数。源条目消失、版本或计数不匹配、已过期或目标窗口已存在时返回 false。源客户端须采用原路由并连接原进程。采集时须记录同一条目的 CAS、计数和可信截止时间。二进制协议可核对版本和值,截止时间仍来自可信快照。 + 如果仅支持二进制协议的源节点已在可保留的内存文件上启用 [Memcached 热重启](https://docs.memcached.org/features/restart/),可在独占切换期间通过现有 Meta Text 导入器读取恢复后的窗口。保持客户端暂停并排空在途写入。向源进程发送 `SIGUSR1` 以正常停机,等待主机时钟超过记录的停机秒数,再使用同一个内存文件和兼容的 slab、CAS 设置重启,并开放隔离的 Meta Text 监听。监听应启用认证或限制为可信本机访问。确认源条目确实恢复后再导入。Memcached 1.6.45 回环测试保留了限时窗口的原始截止时间和永久窗口的无截止状态,停机期间已过期的窗口也未恢复。此方式要求在写入旧窗口前已启用热重启。 对于 Redisson 3.12.5 的 `RMapCache` 重试区域,在同一独占切换阶段使用原缓存和主体调用 `migrateLegacyWindow`。导入复制原计数、条目固定截止时间、空闲策略和当前空闲截止时间,读取时不延长源窗口。若整个 Map 更早过期,使用更早的截止时间。同一 Redis 部署内使用独立的目标命名空间。 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java index 249fdcc..3e05b9a 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java @@ -171,11 +171,38 @@ public boolean migrateLegacyWindowFromMetaConnection(String principal, Socket so * @return true when an active snapshot was copied to an empty destination */ public boolean migrateLegacyWindowFromSnapshot(String principal, int count, long deadlineEpochSecond) { + MemcachedLegacyWindow legacy = verifiedSnapshot(count, deadlineEpochSecond); + return migrateLegacyWindow(principal, ignored -> legacy); + } + + /** + * Imports an authoritative expiry snapshot after checking the live source version and count. + * Pause retry clients and drain outstanding writes before collecting and importing the snapshot. + * The binary protocol can check the entry version and value. The original deadline must come + * from the same trusted snapshot. Read the original process before it restarts or the key moves. + * + * @param principal original string principal in the J2Cache region + * @param source caller-managed client on the legacy servers with the original routing and authentication + * @param sourceCas nonzero CAS of the source entry recorded with the snapshot + * @param count original nonnegative retry count + * @param deadlineEpochSecond original absolute expiry, or zero for a persistent entry + * @return true when the matching active entry was copied to an empty destination + */ + public boolean migrateLegacyWindowFromSnapshot(String principal, MemcachedClient source, long sourceCas, + int count, long deadlineEpochSecond) { + Objects.requireNonNull(source, "source"); + if (sourceCas == 0) { + throw new IllegalArgumentException("The Memcached snapshot requires a nonzero source CAS"); + } + MemcachedLegacyWindow legacy = verifiedSnapshot(count, deadlineEpochSecond); + return migrateLegacyWindow(principal, key -> MemcachedLegacyWindow.readMatchingVersion(source, key, sourceCas, legacy)); + } + + private static MemcachedLegacyWindow verifiedSnapshot(int count, long deadlineEpochSecond) { if (count < 0 || deadlineEpochSecond < 0 || deadlineEpochSecond > Integer.MAX_VALUE) { throw new IllegalArgumentException("Invalid Memcached snapshot retry count or expiry"); } - MemcachedLegacyWindow legacy = new MemcachedLegacyWindow(count, (int) deadlineEpochSecond); - return migrateLegacyWindow(principal, ignored -> legacy); + return new MemcachedLegacyWindow(count, (int) deadlineEpochSecond); } private boolean migrateLegacyWindow(String principal, LegacyRead source) { @@ -202,7 +229,8 @@ private boolean migrateLegacyWindow(String principal, LegacyRead source) { @FunctionalInterface private interface LegacyRead { - MemcachedLegacyWindow read(String key) throws IOException; + MemcachedLegacyWindow read(String key) + throws IOException, InterruptedException, TimeoutException, MemcachedException; } private Window newWindow() { diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java index 4f634c0..acdd14c 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java @@ -9,15 +9,19 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Objects; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import lombok.Value; import net.oschina.j2cache.util.SerializationUtils; +import net.rubyeye.xmemcached.GetsResponse; +import net.rubyeye.xmemcached.MemcachedClient; +import net.rubyeye.xmemcached.exception.MemcachedException; import net.rubyeye.xmemcached.transcoders.CachedData; import net.rubyeye.xmemcached.transcoders.SerializingTranscoder; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.cache.CacheException; -/** A read-only Memcached meta snapshot of the original J2Cache entry. */ +/** The original J2Cache retry count and Memcached deadline. */ @Value class MemcachedLegacyWindow { @@ -85,6 +89,20 @@ static MemcachedLegacyWindow read(Socket socket, String key) throws IOException private static MemcachedLegacyWindow decode(byte[] payload, int flags, int deadline) throws IOException { Object raw = TRANSCODER.decode(new CachedData(flags, payload)); + return new MemcachedLegacyWindow(counterValue(raw), deadline); + } + + static MemcachedLegacyWindow readMatchingVersion(MemcachedClient source, String key, long sourceCas, + MemcachedLegacyWindow expected) + throws TimeoutException, InterruptedException, MemcachedException, IOException { + GetsResponse current = source.gets(key, TRANSCODER); + if (Objects.isNull(current) || current.getCas() != sourceCas) { + return null; + } + return counterValue(current.getValue()) == expected.getCount() ? expected : null; + } + + private static int counterValue(Object raw) throws IOException { if (!(raw instanceof byte[])) { throw new CacheException("Legacy Memcached value must contain J2Cache bytes"); } @@ -92,7 +110,7 @@ private static MemcachedLegacyWindow decode(byte[] payload, int flags, int deadl if (!(counter instanceof AtomicInteger) || ((AtomicInteger) counter).get() < 0) { throw new CacheException("Legacy Memcached value must contain a nonnegative retry counter"); } - return new MemcachedLegacyWindow(((AtomicInteger) counter).get(), deadline); + return ((AtomicInteger) counter).get(); } private static long time(DataInputStream input, OutputStream output) throws IOException { diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java index fb083c5..3ce127e 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java @@ -216,9 +216,23 @@ public void refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter() throws E assertThrows(CacheException.class, () -> store.migrateLegacyWindow(principal, AddrUtil.getOneAddress(binaryEndpoint))); assertNull(firstClient.get(target, new StringTranscoder())); - assertTrue(store.migrateLegacyWindowFromSnapshot(principal, 3, sourceDeadline)); - assertEquals(4, store.reserve(principal).getCount()); - assertEquals(originalCas, legacy.gets(legacyKey, transcoder).getCas()); + assertThrows(IllegalArgumentException.class, + () -> store.migrateLegacyWindowFromSnapshot(principal, legacy, 0, 3, sourceDeadline)); + assertFalse(store.migrateLegacyWindowFromSnapshot("missing", legacy, originalCas, 3, sourceDeadline)); + assertFalse(store.migrateLegacyWindowFromSnapshot(principal, legacy, originalCas, 2, sourceDeadline)); + assertNull(firstClient.get(target, new StringTranscoder())); + assertTrue(legacy.set(legacyKey, sourceDeadline, counter, transcoder)); + long currentCas = legacy.gets(legacyKey, transcoder).getCas(); + assertNotEquals(originalCas, currentCas); + assertFalse(store.migrateLegacyWindowFromSnapshot(principal, legacy, originalCas, 3, sourceDeadline)); + assertNull(firstClient.get(target, new StringTranscoder())); + + assertTrue(store.migrateLegacyWindowFromSnapshot(principal, legacy, currentCas, 3, sourceDeadline)); + assertFalse(store.migrateLegacyWindowFromSnapshot(principal, legacy, currentCas, 3, sourceDeadline)); + Attempt migrated = store.reserve(principal); + assertEquals(4, migrated.getCount()); + assertEquals(sourceDeadline + ":4:" + migrated.getWindowId(), firstClient.get(target, new StringTranscoder())); + assertEquals(currentCas, legacy.gets(legacyKey, transcoder).getCas()); } finally { legacy.shutdown(); }