Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ jobs:
for name in (
"importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline",
"refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter",
"importsAuthoritativeSnapshotWithTheOriginalServerDeadline",
"importsLegacyWindowsAfterBinarySourceWarmRestart",
):
case = suite.find(f'./testcase[@name="{name}"]')
Expand Down
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,11 @@ 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.

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.

Expand All @@ -213,6 +217,10 @@ 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.

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.
Expand Down
10 changes: 9 additions & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,11 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher());

对于现有 Ehcache 2 重试缓存,先停止访问该区域的全部旧版客户端,再启用共享重试存储,并沿用原区域及主体键。首次预留在键锁内转换已保存的旧计数,计入本次尝试,并保留原 TTL 截止时间和配置的空闲过期策略。集群部署使用强一致性区域。

对于原生 Ehcache 3,暂停所有重试客户端并排空在途写入,每个区域只允许一个迁移写入方。使用原缓存对已知主体调用 `migrateLegacyWindow`。区域须使用仅在创建时设置的过期策略或永不过期策略。`Serializable` 等可接受旧计数和新窗口的区域直接保存新窗口。`AtomicInteger` 类型区域保存含窗口 ID 的可序列化子类型,要求序列化器保留该类型。活跃条目在原位置替换,保留原截止时间。会在写入时重置截止时间的策略需要独立切换方案。
对于原生 Ehcache 3,暂停所有重试客户端并排空在途写入,每个区域只允许一个迁移写入方。使用原缓存对已知主体调用 `migrateLegacyWindow`。区域须使用仅在创建时设置的过期策略或永不过期策略。`Serializable` 等可接受旧计数和新窗口的区域直接保存新窗口。`AtomicInteger` 类型区域保存含窗口 ID 的可序列化子类型,要求序列化器保留该类型。活跃条目在原位置替换,保留原截止时间。

旧区域的 TTL 或 TTI 若会因写入或访问续期,且能确认有限上界,可在维护窗口内排空切换。暂停所有可能访问旧重试区域的客户端和后台任务,等在途操作全部完成。从该时点起,至少等待所有来源区域配置中最长的一段有效期,并计入部署所需的时钟余量。等待结束后,在独立区域启用新存储并配置创建窗口。旧区域保持原状,已有计数按自身策略自然到期。该路径需要维护停顿,并确认新区域采用固定窗口。存在永不过期条目、无法证明上界的自定义策略,或必须继续保留续期行为时,需另选切换方式。

回滚时保持客户端暂停并排空在途写入,再对已知主体调用 `restoreLegacyWindow`。缓存区域必须接受 `AtomicInteger`。活跃窗口恢复为普通旧版计数,保留当前次数和原截止时间。缺失、已过期或已经恢复的条目会跳过。

Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所有集群成员须部署重试存储模块,并沿用原 IMap 和主体键。首次预留会原子转换旧计数,保留剩余 TTL,并按原策略刷新空闲时间。使用 3.12 适配器时需传入 IMap 配置的最大空闲时长。

Expand All @@ -213,6 +217,10 @@ J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字

J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由选择保存旧值的源节点。对允许 Meta Text 协议的可信源节点,可向 `migrateLegacyWindow` 传入地址。需要认证时,先认证专用 Meta Text 连接,设置有限的读取超时,再传给 `migrateLegacyWindowFromMetaConnection`。调用方负责认证、传输安全和关闭连接。连接上应没有在途命令,并由单个调用方顺序读取。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议的节点(包括要求二进制 SASL 的节点)仍需要独立迁移方式,因为其 GET 操作不返回原有效期。 如果能确认所有旧窗口的有效期上限,先暂停旧、新客户端并排空在途写入,等待所有源节点上的旧窗口过期,再启用新存储。存在永久窗口或无法确认有效期上限时,应继续使用旧存储,直到取得可信的到期时间快照。二进制 GET 返回计数和 CAS,无法区分限时窗口和永久窗口。

独占切换期间可调用 `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 部署内使用独立的目标命名空间。
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,51 @@ 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) {
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");
}
return new MemcachedLegacyWindow(count, (int) deadlineEpochSecond);
}

private boolean migrateLegacyWindow(String principal, LegacyRead source) {
Objects.requireNonNull(principal, "principal");
try {
Expand All @@ -184,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() {
Expand Down
Loading
Loading