Browse Source
业务键 + provider 请求键双锁:业务键不带 provider,直连与聚合器共用; provider 键只防单 provider 内重试。 - 新增 idempotency 包:WriteScope / WriteResult / IdempotencyGuard - 新增 SPI:IdempotencyStore 及 Claim / Record / Status 四态 - ChannelSdk.writes() 装配守卫;未注入 store 时显式失败,无降级路径 - 崩溃窗口由 provider 键恢复:平台已写但业务键未记成功时回放,不重复写 - testkit 新增 InMemoryIdempotencyStore / MutableClock,junit 改为 test 作用域 Co-Authored-By: Claude <noreply@anthropic.com>feature/supplier-lingxing
13 changed files with 1003 additions and 3 deletions
@ -0,0 +1,182 @@ |
|||||||
|
package common.ecommerce.idempotency; |
||||||
|
|
||||||
|
import common.ecommerce.error.ChannelException; |
||||||
|
import common.ecommerce.error.CrossProviderConflictException; |
||||||
|
import common.ecommerce.error.IdempotencyConflictException; |
||||||
|
import common.ecommerce.spi.IdempotencyClaim; |
||||||
|
import common.ecommerce.spi.IdempotencyRecord; |
||||||
|
import common.ecommerce.spi.IdempotencyStatus; |
||||||
|
import common.ecommerce.spi.IdempotencyStore; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
import java.time.Instant; |
||||||
|
import java.util.Objects; |
||||||
|
import java.util.Optional; |
||||||
|
import java.util.UUID; |
||||||
|
import java.util.function.Function; |
||||||
|
import java.util.function.Supplier; |
||||||
|
|
||||||
|
/** |
||||||
|
* 写操作幂等守卫:业务键 + provider 请求键双锁。 |
||||||
|
* |
||||||
|
* <pre> |
||||||
|
* 1. 抢占业务键(不带 provider)——直连与聚合器共用,同一业务动作只成功一次 |
||||||
|
* 2. 抢占 provider 请求键(带 provider)——单 provider 内重试去重 |
||||||
|
* 3. 执行平台写操作 |
||||||
|
* 4. 先记 provider 键成功,再记业务键成功;中途崩溃时下次重试能靠 provider 键识别「已写过」 |
||||||
|
* </pre> |
||||||
|
* |
||||||
|
* <p>语义:</p> |
||||||
|
* <ul> |
||||||
|
* <li>业务键已 SUCCEEDED:返回 {@link WriteResult.Outcome#ALREADY_COMPLETED},不视为失败</li> |
||||||
|
* <li>业务键已完成但由另一个 provider 完成:抛 {@link CrossProviderConflictException},不自动跨 provider 重试</li> |
||||||
|
* <li>业务键 IN_PROGRESS:抛 {@link IdempotencyConflictException},拒绝并发重复</li> |
||||||
|
* <li>业务键 FAILED_FINAL:抛终态异常,需人工介入</li> |
||||||
|
* <li>可重试失败:两个键记为 FAILED_RETRYABLE,下次调用可重新抢占</li> |
||||||
|
* </ul> |
||||||
|
* |
||||||
|
* <p>守卫不碰平台协议,也不自行重试;重试由宿主调度决定。</p> |
||||||
|
*/ |
||||||
|
public final class IdempotencyGuard { |
||||||
|
|
||||||
|
public static final long DEFAULT_CLAIM_TTL_SECONDS = 300L; |
||||||
|
|
||||||
|
private final IdempotencyStore store; |
||||||
|
private final String owner; |
||||||
|
private final Clock clock; |
||||||
|
private final long claimTtlSeconds; |
||||||
|
|
||||||
|
public IdempotencyGuard(IdempotencyStore store, Clock clock) { |
||||||
|
this(store, UUID.randomUUID().toString(), clock, DEFAULT_CLAIM_TTL_SECONDS); |
||||||
|
} |
||||||
|
|
||||||
|
public IdempotencyGuard(IdempotencyStore store, String owner, Clock clock, long claimTtlSeconds) { |
||||||
|
this.store = Objects.requireNonNull(store, "store"); |
||||||
|
this.owner = Objects.requireNonNull(owner, "owner"); |
||||||
|
this.clock = Objects.requireNonNull(clock, "clock"); |
||||||
|
if (claimTtlSeconds <= 0) { |
||||||
|
throw new IllegalArgumentException("claimTtlSeconds must be positive"); |
||||||
|
} |
||||||
|
this.claimTtlSeconds = claimTtlSeconds; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 执行一次写操作。 |
||||||
|
* |
||||||
|
* @param scope 标识维度 |
||||||
|
* @param action 平台写操作;抛 {@link ChannelException} 时按其 {@code retryable()} 决定是否可重试 |
||||||
|
* @param resultRef 从执行结果中提取结果引用(订单号 / 包裹号等),可为 null |
||||||
|
*/ |
||||||
|
public <T> WriteResult<T> execute(WriteScope scope, Supplier<T> action, Function<? super T, String> resultRef) { |
||||||
|
Objects.requireNonNull(scope, "scope"); |
||||||
|
Objects.requireNonNull(action, "action"); |
||||||
|
Objects.requireNonNull(resultRef, "resultRef"); |
||||||
|
|
||||||
|
final String businessKey = scope.businessKey(); |
||||||
|
final String providerKey = scope.providerKey(); |
||||||
|
final Instant now = Instant.now(clock); |
||||||
|
|
||||||
|
// 1) 业务键:跨 provider 的最终裁决
|
||||||
|
IdempotencyClaim business = store.claim(businessKey, owner, scope.provider(), now, claimTtlSeconds); |
||||||
|
if (!business.acquired()) { |
||||||
|
return handleNotAcquired(scope, business, businessKey, providerKey); |
||||||
|
} |
||||||
|
|
||||||
|
// 2) provider 键:识别「平台已写、业务键没来得及记成功」的崩溃窗口
|
||||||
|
IdempotencyClaim provider = store.claim(providerKey, owner, scope.provider(), now, claimTtlSeconds); |
||||||
|
if (!provider.acquired()) { |
||||||
|
if (provider.outcome() == IdempotencyClaim.Outcome.SUCCEEDED) { |
||||||
|
store.complete(businessKey, owner, provider.record().resultRef(), Instant.now(clock)); |
||||||
|
return replay(scope, provider.record(), businessKey, providerKey); |
||||||
|
} |
||||||
|
store.fail(businessKey, owner, provider.outcome() != IdempotencyClaim.Outcome.FAILED_FINAL, |
||||||
|
Instant.now(clock)); |
||||||
|
return handleNotAcquired(scope, provider, businessKey, providerKey); |
||||||
|
} |
||||||
|
|
||||||
|
// 3) 执行
|
||||||
|
T value; |
||||||
|
try { |
||||||
|
value = action.get(); |
||||||
|
} catch (RuntimeException e) { |
||||||
|
boolean retryable = isRetryable(e); |
||||||
|
store.fail(providerKey, owner, retryable, Instant.now(clock)); |
||||||
|
store.fail(businessKey, owner, retryable, Instant.now(clock)); |
||||||
|
throw e; |
||||||
|
} |
||||||
|
|
||||||
|
// 4) 先记 provider 键,再记业务键
|
||||||
|
String ref = resultRef.apply(value); |
||||||
|
store.complete(providerKey, owner, ref, Instant.now(clock)); |
||||||
|
store.complete(businessKey, owner, ref, Instant.now(clock)); |
||||||
|
return WriteResult.executed(value, ref, businessKey, providerKey); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- internals
|
||||||
|
|
||||||
|
private <T> WriteResult<T> handleNotAcquired(WriteScope scope, IdempotencyClaim claim, |
||||||
|
String businessKey, String providerKey) { |
||||||
|
IdempotencyRecord record = claim.record(); |
||||||
|
switch (claim.outcome()) { |
||||||
|
case SUCCEEDED: |
||||||
|
return replay(scope, record, businessKey, providerKey); |
||||||
|
case IN_PROGRESS: |
||||||
|
throw new IdempotencyConflictException(ChannelException.builder() |
||||||
|
.message("write already in progress: " + providerKey) |
||||||
|
.operation(scope.action()) |
||||||
|
.provider(scope.provider().name()) |
||||||
|
.omsStoreId(scope.omsStoreId()) |
||||||
|
.platform(scope.platform()), businessKey); |
||||||
|
case FAILED_FINAL: |
||||||
|
throw ChannelException.builder() |
||||||
|
.message("previous attempt failed permanently, manual intervention required: " + businessKey) |
||||||
|
.operation(scope.action()) |
||||||
|
.provider(scope.provider().name()) |
||||||
|
.omsStoreId(scope.omsStoreId()) |
||||||
|
.platform(scope.platform()) |
||||||
|
.retryable(false) |
||||||
|
.build(); |
||||||
|
default: |
||||||
|
throw new IllegalStateException("unexpected claim outcome " + claim.outcome() + " for " + businessKey); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
private <T> WriteResult<T> replay(WriteScope scope, IdempotencyRecord record, |
||||||
|
String businessKey, String providerKey) { |
||||||
|
if (record.provider() != null && record.provider() != scope.provider()) { |
||||||
|
throw new CrossProviderConflictException(ChannelException.builder() |
||||||
|
.message("business action already completed by " + record.provider() |
||||||
|
+ ", requested via " + scope.provider() + ": " + businessKey) |
||||||
|
.operation(scope.action()) |
||||||
|
.provider(scope.provider().name()) |
||||||
|
.omsStoreId(scope.omsStoreId()) |
||||||
|
.platform(scope.platform()) |
||||||
|
.retryable(false), record.provider().name()); |
||||||
|
} |
||||||
|
return WriteResult.alreadyCompleted(record.resultRef(), businessKey, providerKey); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 只有显式标记可重试的 {@link ChannelException} 才允许重跑。 |
||||||
|
* |
||||||
|
* <p>超时等「结果未知」的异常由适配器先回查再抛:确认未写入抛可重试异常, |
||||||
|
* 确认已写入应当返回成功,而不是抛异常。</p> |
||||||
|
*/ |
||||||
|
private static boolean isRetryable(RuntimeException e) { |
||||||
|
return e instanceof ChannelException && ((ChannelException) e).retryable(); |
||||||
|
} |
||||||
|
|
||||||
|
public String owner() { |
||||||
|
return owner; |
||||||
|
} |
||||||
|
|
||||||
|
/** 只读查询,供运维排查。 */ |
||||||
|
public Optional<IdempotencyRecord> status(WriteScope scope) { |
||||||
|
return store.get(scope.businessKey()); |
||||||
|
} |
||||||
|
|
||||||
|
/** 该状态是否可安全重跑。 */ |
||||||
|
public static boolean isRetryableStatus(IdempotencyStatus status) { |
||||||
|
return status == IdempotencyStatus.FAILED_RETRYABLE; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,71 @@ |
|||||||
|
package common.ecommerce.idempotency; |
||||||
|
|
||||||
|
/** |
||||||
|
* 写操作执行结果。 |
||||||
|
* |
||||||
|
* <p>重复调用不视为失败:{@link Outcome#ALREADY_COMPLETED} 表示该业务动作此前已成功, |
||||||
|
* 本次没有再次调用平台。</p> |
||||||
|
*/ |
||||||
|
public final class WriteResult<T> { |
||||||
|
|
||||||
|
public enum Outcome { |
||||||
|
/** 本次真正执行了平台写操作。 */ |
||||||
|
EXECUTED, |
||||||
|
/** 此前已成功,本次直接回放,未调用平台。 */ |
||||||
|
ALREADY_COMPLETED |
||||||
|
} |
||||||
|
|
||||||
|
private final Outcome outcome; |
||||||
|
private final T value; |
||||||
|
private final String resultRef; |
||||||
|
private final String businessKey; |
||||||
|
private final String providerKey; |
||||||
|
|
||||||
|
private WriteResult(Outcome outcome, T value, String resultRef, String businessKey, String providerKey) { |
||||||
|
this.outcome = outcome; |
||||||
|
this.value = value; |
||||||
|
this.resultRef = resultRef; |
||||||
|
this.businessKey = businessKey; |
||||||
|
this.providerKey = providerKey; |
||||||
|
} |
||||||
|
|
||||||
|
public static <T> WriteResult<T> executed(T value, String resultRef, String businessKey, String providerKey) { |
||||||
|
return new WriteResult<T>(Outcome.EXECUTED, value, resultRef, businessKey, providerKey); |
||||||
|
} |
||||||
|
|
||||||
|
/** 回放:没有本次调用的返回值,只有上次记录的结果引用。 */ |
||||||
|
public static <T> WriteResult<T> alreadyCompleted(String resultRef, String businessKey, String providerKey) { |
||||||
|
return new WriteResult<T>(Outcome.ALREADY_COMPLETED, null, resultRef, businessKey, providerKey); |
||||||
|
} |
||||||
|
|
||||||
|
public Outcome outcome() { |
||||||
|
return outcome; |
||||||
|
} |
||||||
|
|
||||||
|
/** 本次执行结果;ALREADY_COMPLETED 时为 null。 */ |
||||||
|
public T value() { |
||||||
|
return value; |
||||||
|
} |
||||||
|
|
||||||
|
/** 结果引用(订单号 / 包裹号等);可能为 null。 */ |
||||||
|
public String resultRef() { |
||||||
|
return resultRef; |
||||||
|
} |
||||||
|
|
||||||
|
public String businessKey() { |
||||||
|
return businessKey; |
||||||
|
} |
||||||
|
|
||||||
|
public String providerKey() { |
||||||
|
return providerKey; |
||||||
|
} |
||||||
|
|
||||||
|
public boolean alreadyCompleted() { |
||||||
|
return outcome == Outcome.ALREADY_COMPLETED; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public String toString() { |
||||||
|
return "WriteResult{" + outcome + (resultRef == null ? "" : " -> " + resultRef) + '}'; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,92 @@ |
|||||||
|
package common.ecommerce.idempotency; |
||||||
|
|
||||||
|
import common.ecommerce.model.support.CanonicalKeys; |
||||||
|
import common.ecommerce.model.ChannelProvider; |
||||||
|
import common.ecommerce.model.Platform; |
||||||
|
|
||||||
|
import java.util.Objects; |
||||||
|
|
||||||
|
/** |
||||||
|
* 一次写操作的标识维度,由业务键与 provider 请求键共同组成。 |
||||||
|
* |
||||||
|
* <ul> |
||||||
|
* <li><b>业务键</b>:{@code platform + omsStoreId + businessRef + action},不带 provider, |
||||||
|
* 直连与聚合器共用,保证同一业务动作只成功一次</li> |
||||||
|
* <li><b>provider 请求键</b>:{@code provider + platform + externalStoreId + operation + providerRef}, |
||||||
|
* 只防单 provider 内的重复请求/重试</li> |
||||||
|
* </ul> |
||||||
|
*/ |
||||||
|
public final class WriteScope { |
||||||
|
|
||||||
|
private final ChannelProvider provider; |
||||||
|
private final Platform platform; |
||||||
|
private final String omsStoreId; |
||||||
|
private final String externalStoreId; |
||||||
|
private final String action; |
||||||
|
private final String businessRef; |
||||||
|
|
||||||
|
private WriteScope(ChannelProvider provider, Platform platform, String omsStoreId, String externalStoreId, |
||||||
|
String action, String businessRef) { |
||||||
|
this.provider = Objects.requireNonNull(provider, "provider"); |
||||||
|
this.platform = Objects.requireNonNull(platform, "platform"); |
||||||
|
this.omsStoreId = requireText(omsStoreId, "omsStoreId"); |
||||||
|
this.externalStoreId = requireText(externalStoreId, "externalStoreId"); |
||||||
|
this.action = requireText(action, "action"); |
||||||
|
this.businessRef = requireText(businessRef, "businessRef"); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* @param businessRef 业务自然键,如 {@code PO-1:pkg-1} 或 {@code RET-1:ITEM-1:REFUND-1}; |
||||||
|
* <b>不得使用金额</b> |
||||||
|
*/ |
||||||
|
public static WriteScope of(ChannelProvider provider, Platform platform, String omsStoreId, |
||||||
|
String externalStoreId, String action, String businessRef) { |
||||||
|
return new WriteScope(provider, platform, omsStoreId, externalStoreId, action, businessRef); |
||||||
|
} |
||||||
|
|
||||||
|
public ChannelProvider provider() { |
||||||
|
return provider; |
||||||
|
} |
||||||
|
|
||||||
|
public Platform platform() { |
||||||
|
return platform; |
||||||
|
} |
||||||
|
|
||||||
|
public String omsStoreId() { |
||||||
|
return omsStoreId; |
||||||
|
} |
||||||
|
|
||||||
|
public String externalStoreId() { |
||||||
|
return externalStoreId; |
||||||
|
} |
||||||
|
|
||||||
|
public String action() { |
||||||
|
return action; |
||||||
|
} |
||||||
|
|
||||||
|
public String businessRef() { |
||||||
|
return businessRef; |
||||||
|
} |
||||||
|
|
||||||
|
/** 跨 provider 的业务幂等键。 */ |
||||||
|
public String businessKey() { |
||||||
|
return CanonicalKeys.businessIdempotencyKey(platform, omsStoreId, businessRef, action); |
||||||
|
} |
||||||
|
|
||||||
|
/** 单 provider 内的请求幂等键。 */ |
||||||
|
public String providerKey() { |
||||||
|
return CanonicalKeys.providerRequestKey(provider, platform, externalStoreId, action, businessRef); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public String toString() { |
||||||
|
return provider + ":" + platform + ":" + omsStoreId + ":" + action + ":" + businessRef; |
||||||
|
} |
||||||
|
|
||||||
|
private static String requireText(String value, String name) { |
||||||
|
if (value == null || value.trim().isEmpty()) { |
||||||
|
throw new IllegalArgumentException(name + " must not be blank"); |
||||||
|
} |
||||||
|
return value.trim(); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,57 @@ |
|||||||
|
package common.ecommerce.spi; |
||||||
|
|
||||||
|
/** |
||||||
|
* 抢占幂等键的结果。 |
||||||
|
* |
||||||
|
* <p>宿主实现 {@link IdempotencyStore#claim} 时按以下规则返回:</p> |
||||||
|
* <ul> |
||||||
|
* <li>无记录,或记录为 FAILED_RETRYABLE,或 IN_PROGRESS 已超过 TTL:{@link Outcome#ACQUIRED},并写入 IN_PROGRESS</li> |
||||||
|
* <li>记录为 IN_PROGRESS 且未过期:{@link Outcome#IN_PROGRESS},拒绝并发执行</li> |
||||||
|
* <li>记录为 SUCCEEDED:{@link Outcome#SUCCEEDED},回放结果</li> |
||||||
|
* <li>记录为 FAILED_FINAL:{@link Outcome#FAILED_FINAL},需人工介入</li> |
||||||
|
* </ul> |
||||||
|
*/ |
||||||
|
public final class IdempotencyClaim { |
||||||
|
|
||||||
|
public enum Outcome { |
||||||
|
ACQUIRED, |
||||||
|
IN_PROGRESS, |
||||||
|
SUCCEEDED, |
||||||
|
FAILED_FINAL |
||||||
|
} |
||||||
|
|
||||||
|
private final Outcome outcome; |
||||||
|
private final IdempotencyRecord record; |
||||||
|
|
||||||
|
private IdempotencyClaim(Outcome outcome, IdempotencyRecord record) { |
||||||
|
this.outcome = outcome; |
||||||
|
this.record = record; |
||||||
|
} |
||||||
|
|
||||||
|
/** 抢占成功;record 为 null(没有历史记录)。 */ |
||||||
|
public static IdempotencyClaim acquire() { |
||||||
|
return new IdempotencyClaim(Outcome.ACQUIRED, null); |
||||||
|
} |
||||||
|
|
||||||
|
public static IdempotencyClaim of(Outcome outcome, IdempotencyRecord record) { |
||||||
|
return new IdempotencyClaim(outcome, record); |
||||||
|
} |
||||||
|
|
||||||
|
public Outcome outcome() { |
||||||
|
return outcome; |
||||||
|
} |
||||||
|
|
||||||
|
/** 已有记录;ACQUIRED 时为 null。 */ |
||||||
|
public IdempotencyRecord record() { |
||||||
|
return record; |
||||||
|
} |
||||||
|
|
||||||
|
public boolean acquired() { |
||||||
|
return outcome == Outcome.ACQUIRED; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public String toString() { |
||||||
|
return "IdempotencyClaim{" + outcome + (record == null ? "" : " " + record) + '}'; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,69 @@ |
|||||||
|
package common.ecommerce.spi; |
||||||
|
|
||||||
|
import common.ecommerce.model.ChannelProvider; |
||||||
|
|
||||||
|
import java.time.Instant; |
||||||
|
import java.util.Objects; |
||||||
|
|
||||||
|
/** |
||||||
|
* 幂等键的当前记录。 |
||||||
|
* |
||||||
|
* <p>{@code provider} 记录该动作最终由哪条接入通道完成,用于识别跨 provider |
||||||
|
* 重复执行;{@code owner} 是抢占该键的实例标识,用于判断并发。</p> |
||||||
|
*/ |
||||||
|
public final class IdempotencyRecord { |
||||||
|
|
||||||
|
private final String key; |
||||||
|
private final IdempotencyStatus status; |
||||||
|
private final ChannelProvider provider; |
||||||
|
private final String owner; |
||||||
|
private final String resultRef; |
||||||
|
private final Instant updatedAt; |
||||||
|
|
||||||
|
private IdempotencyRecord(String key, IdempotencyStatus status, ChannelProvider provider, |
||||||
|
String owner, String resultRef, Instant updatedAt) { |
||||||
|
this.key = Objects.requireNonNull(key, "key"); |
||||||
|
this.status = Objects.requireNonNull(status, "status"); |
||||||
|
this.provider = provider; |
||||||
|
this.owner = owner; |
||||||
|
this.resultRef = resultRef; |
||||||
|
this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt"); |
||||||
|
} |
||||||
|
|
||||||
|
public static IdempotencyRecord of(String key, IdempotencyStatus status, ChannelProvider provider, |
||||||
|
String owner, String resultRef, Instant updatedAt) { |
||||||
|
return new IdempotencyRecord(key, status, provider, owner, resultRef, updatedAt); |
||||||
|
} |
||||||
|
|
||||||
|
public String key() { |
||||||
|
return key; |
||||||
|
} |
||||||
|
|
||||||
|
public IdempotencyStatus status() { |
||||||
|
return status; |
||||||
|
} |
||||||
|
|
||||||
|
/** 完成该动作的 provider;IN_PROGRESS 时为抢占方。 */ |
||||||
|
public ChannelProvider provider() { |
||||||
|
return provider; |
||||||
|
} |
||||||
|
|
||||||
|
public String owner() { |
||||||
|
return owner; |
||||||
|
} |
||||||
|
|
||||||
|
/** 结果引用(订单号 / 包裹号等),不保存完整业务结果。 */ |
||||||
|
public String resultRef() { |
||||||
|
return resultRef; |
||||||
|
} |
||||||
|
|
||||||
|
public Instant updatedAt() { |
||||||
|
return updatedAt; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public String toString() { |
||||||
|
return "IdempotencyRecord{" + key + " " + status + " by " + provider + '/' + owner |
||||||
|
+ (resultRef == null ? "" : " -> " + resultRef) + '}'; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,18 @@ |
|||||||
|
package common.ecommerce.spi; |
||||||
|
|
||||||
|
/** |
||||||
|
* 幂等键状态。 |
||||||
|
* |
||||||
|
* <p>写操作按「抢占 → 执行 → 记录结果」流转,只有 SUCCEEDED 可以回放结果。</p> |
||||||
|
*/ |
||||||
|
public enum IdempotencyStatus { |
||||||
|
|
||||||
|
/** 已抢占,执行中;并发重复请求被拒绝。 */ |
||||||
|
IN_PROGRESS, |
||||||
|
/** 已成功;重复请求直接回放结果。 */ |
||||||
|
SUCCEEDED, |
||||||
|
/** 可重试失败;允许再次抢占重跑。 */ |
||||||
|
FAILED_RETRYABLE, |
||||||
|
/** 终态失败;需人工介入,不再自动重试。 */ |
||||||
|
FAILED_FINAL |
||||||
|
} |
||||||
@ -0,0 +1,34 @@ |
|||||||
|
package common.ecommerce.spi; |
||||||
|
|
||||||
|
import common.ecommerce.model.ChannelProvider; |
||||||
|
|
||||||
|
import java.time.Instant; |
||||||
|
import java.util.Optional; |
||||||
|
|
||||||
|
/** |
||||||
|
* 幂等存储 SPI。宿主实现(典型 MySQL / Redis),SDK 只调用。 |
||||||
|
* |
||||||
|
* <p>实现必须保证 {@link #claim} 的原子性(唯一索引或 Redis SETNX):并发抢占同一键时 |
||||||
|
* 只有一个调用能得到 {@link IdempotencyClaim.Outcome#ACQUIRED}。</p> |
||||||
|
*/ |
||||||
|
public interface IdempotencyStore { |
||||||
|
|
||||||
|
/** |
||||||
|
* 抢占幂等键。 |
||||||
|
* |
||||||
|
* @param key 幂等键(业务键或 provider 请求键) |
||||||
|
* @param owner 抢占方实例标识 |
||||||
|
* @param provider 接入通道,写入记录用于识别跨 provider 重复 |
||||||
|
* @param now 当前时间(UTC) |
||||||
|
* @param ttlSeconds 抢占后无结果的最长保留时间,过期视为可重新抢占 |
||||||
|
*/ |
||||||
|
IdempotencyClaim claim(String key, String owner, ChannelProvider provider, Instant now, long ttlSeconds); |
||||||
|
|
||||||
|
/** 执行成功,记录结果引用。只有当前 owner 可以写入。 */ |
||||||
|
void complete(String key, String owner, String resultRef, Instant now); |
||||||
|
|
||||||
|
/** 执行失败;{@code retryable=false} 记为终态,不再自动重试。 */ |
||||||
|
void fail(String key, String owner, boolean retryable, Instant now); |
||||||
|
|
||||||
|
Optional<IdempotencyRecord> get(String key); |
||||||
|
} |
||||||
@ -0,0 +1,116 @@ |
|||||||
|
package common.ecommerce.testkit; |
||||||
|
|
||||||
|
import common.ecommerce.model.ChannelProvider; |
||||||
|
import common.ecommerce.spi.IdempotencyClaim; |
||||||
|
import common.ecommerce.spi.IdempotencyRecord; |
||||||
|
import common.ecommerce.spi.IdempotencyStatus; |
||||||
|
import common.ecommerce.spi.IdempotencyStore; |
||||||
|
|
||||||
|
import java.time.Duration; |
||||||
|
import java.time.Instant; |
||||||
|
import java.util.HashMap; |
||||||
|
import java.util.Map; |
||||||
|
import java.util.Optional; |
||||||
|
|
||||||
|
/** |
||||||
|
* 内存版幂等存储,语义与宿主实现一致: |
||||||
|
* |
||||||
|
* <ul> |
||||||
|
* <li>无记录 / FAILED_RETRYABLE / IN_PROGRESS 超过 TTL → 抢占成功</li> |
||||||
|
* <li>IN_PROGRESS 未过期 → 拒绝并发</li> |
||||||
|
* <li>SUCCEEDED → 回放;FAILED_FINAL → 终态</li> |
||||||
|
* </ul> |
||||||
|
* |
||||||
|
* <p>并发相关的行为只能在单 JVM 内验证;真实抢占原子性由宿主唯一索引 / Redis 保证。</p> |
||||||
|
*/ |
||||||
|
public final class InMemoryIdempotencyStore implements IdempotencyStore { |
||||||
|
|
||||||
|
private final Map<String, IdempotencyRecord> records = new HashMap<String, IdempotencyRecord>(); |
||||||
|
private int claimAcquired; |
||||||
|
private int claimRejected; |
||||||
|
|
||||||
|
@Override |
||||||
|
public synchronized IdempotencyClaim claim(String key, String owner, ChannelProvider provider, |
||||||
|
Instant now, long ttlSeconds) { |
||||||
|
IdempotencyRecord existing = records.get(key); |
||||||
|
if (existing == null || isReclaimable(existing, now, ttlSeconds)) { |
||||||
|
records.put(key, IdempotencyRecord.of(key, IdempotencyStatus.IN_PROGRESS, provider, owner, null, now)); |
||||||
|
claimAcquired++; |
||||||
|
return IdempotencyClaim.acquire(); |
||||||
|
} |
||||||
|
claimRejected++; |
||||||
|
switch (existing.status()) { |
||||||
|
case SUCCEEDED: |
||||||
|
return IdempotencyClaim.of(IdempotencyClaim.Outcome.SUCCEEDED, existing); |
||||||
|
case FAILED_FINAL: |
||||||
|
return IdempotencyClaim.of(IdempotencyClaim.Outcome.FAILED_FINAL, existing); |
||||||
|
default: |
||||||
|
return IdempotencyClaim.of(IdempotencyClaim.Outcome.IN_PROGRESS, existing); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public synchronized void complete(String key, String owner, String resultRef, Instant now) { |
||||||
|
IdempotencyRecord current = requireOwned(key, owner); |
||||||
|
records.put(key, IdempotencyRecord.of(key, IdempotencyStatus.SUCCEEDED, |
||||||
|
current.provider(), owner, resultRef, now)); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public synchronized void fail(String key, String owner, boolean retryable, Instant now) { |
||||||
|
IdempotencyRecord current = requireOwned(key, owner); |
||||||
|
records.put(key, IdempotencyRecord.of(key, |
||||||
|
retryable ? IdempotencyStatus.FAILED_RETRYABLE : IdempotencyStatus.FAILED_FINAL, |
||||||
|
current.provider(), owner, current.resultRef(), now)); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public synchronized Optional<IdempotencyRecord> get(String key) { |
||||||
|
return Optional.ofNullable(records.get(key)); |
||||||
|
} |
||||||
|
|
||||||
|
/** 测试辅助:直接写入一条已完成记录,模拟「另一个 provider 早就做过」。 */ |
||||||
|
public synchronized InMemoryIdempotencyStore seedSucceeded(String key, ChannelProvider provider, |
||||||
|
String resultRef, Instant at) { |
||||||
|
records.put(key, IdempotencyRecord.of(key, IdempotencyStatus.SUCCEEDED, provider, "seed", resultRef, at)); |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
/** 测试辅助:直接写入 IN_PROGRESS 记录,模拟并发执行中。 */ |
||||||
|
public synchronized InMemoryIdempotencyStore seedInProgress(String key, ChannelProvider provider, |
||||||
|
String owner, Instant at) { |
||||||
|
records.put(key, IdempotencyRecord.of(key, IdempotencyStatus.IN_PROGRESS, provider, owner, null, at)); |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
public synchronized int claimAcquiredCount() { |
||||||
|
return claimAcquired; |
||||||
|
} |
||||||
|
|
||||||
|
public synchronized int claimRejectedCount() { |
||||||
|
return claimRejected; |
||||||
|
} |
||||||
|
|
||||||
|
public synchronized int size() { |
||||||
|
return records.size(); |
||||||
|
} |
||||||
|
|
||||||
|
private IdempotencyRecord requireOwned(String key, String owner) { |
||||||
|
IdempotencyRecord current = records.get(key); |
||||||
|
if (current == null) { |
||||||
|
throw new IllegalStateException("no idempotency record for " + key); |
||||||
|
} |
||||||
|
if (!current.owner().equals(owner) || current.status() != IdempotencyStatus.IN_PROGRESS) { |
||||||
|
throw new IllegalStateException("record not owned by " + owner + " in progress: " + current); |
||||||
|
} |
||||||
|
return current; |
||||||
|
} |
||||||
|
|
||||||
|
private static boolean isReclaimable(IdempotencyRecord record, Instant now, long ttlSeconds) { |
||||||
|
if (record.status() == IdempotencyStatus.FAILED_RETRYABLE) { |
||||||
|
return true; |
||||||
|
} |
||||||
|
return record.status() == IdempotencyStatus.IN_PROGRESS |
||||||
|
&& !now.isBefore(record.updatedAt().plus(Duration.ofSeconds(ttlSeconds))); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,49 @@ |
|||||||
|
package common.ecommerce.testkit; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
import java.time.Duration; |
||||||
|
import java.time.Instant; |
||||||
|
import java.time.ZoneId; |
||||||
|
import java.time.ZoneOffset; |
||||||
|
|
||||||
|
/** |
||||||
|
* 可推进的时钟。用来验证 TTL、提前续期、水位线等与时间有关的边界。 |
||||||
|
*/ |
||||||
|
public final class MutableClock extends Clock { |
||||||
|
|
||||||
|
private Instant now; |
||||||
|
private final ZoneId zone; |
||||||
|
|
||||||
|
public MutableClock(Instant now, ZoneId zone) { |
||||||
|
this.now = now; |
||||||
|
this.zone = zone; |
||||||
|
} |
||||||
|
|
||||||
|
public static MutableClock atUtc(String iso) { |
||||||
|
return new MutableClock(Instant.parse(iso), ZoneOffset.UTC); |
||||||
|
} |
||||||
|
|
||||||
|
public MutableClock advance(Duration duration) { |
||||||
|
now = now.plus(duration); |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
public void set(Instant instant) { |
||||||
|
this.now = instant; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public ZoneId getZone() { |
||||||
|
return zone; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public Clock withZone(ZoneId zone) { |
||||||
|
return new MutableClock(now, zone); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public Instant instant() { |
||||||
|
return now; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,212 @@ |
|||||||
|
package common.ecommerce.idempotency; |
||||||
|
|
||||||
|
import common.ecommerce.error.ChannelException; |
||||||
|
import common.ecommerce.error.CrossProviderConflictException; |
||||||
|
import common.ecommerce.error.IdempotencyConflictException; |
||||||
|
import common.ecommerce.model.ChannelProvider; |
||||||
|
import common.ecommerce.model.Platform; |
||||||
|
import common.ecommerce.spi.IdempotencyStatus; |
||||||
|
import common.ecommerce.testkit.InMemoryIdempotencyStore; |
||||||
|
import common.ecommerce.testkit.MutableClock; |
||||||
|
import org.junit.jupiter.api.BeforeEach; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.Duration; |
||||||
|
import java.time.Instant; |
||||||
|
import java.util.concurrent.atomic.AtomicInteger; |
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** |
||||||
|
* 双锁幂等守卫的行为:回放、跨 provider 冲突、并发拒绝、可重试失败、TTL 重抢。 |
||||||
|
*/ |
||||||
|
class IdempotencyGuardTest { |
||||||
|
|
||||||
|
private static final Instant T0 = Instant.parse("2026-10-29T00:00:00Z"); |
||||||
|
private static final WriteScope MARK_SHIPPED = WriteScope.of( |
||||||
|
ChannelProvider.LINGXING, Platform.WALMART_SC, "oms-wm-001", "1108413237731", |
||||||
|
"markShipped", "PO-1:pkg-1"); |
||||||
|
|
||||||
|
private InMemoryIdempotencyStore store; |
||||||
|
private MutableClock clock; |
||||||
|
private IdempotencyGuard guard; |
||||||
|
|
||||||
|
@BeforeEach |
||||||
|
void setUp() { |
||||||
|
store = new InMemoryIdempotencyStore(); |
||||||
|
clock = new MutableClock(T0, java.time.ZoneOffset.UTC); |
||||||
|
guard = new IdempotencyGuard(store, "worker-1", clock, 60); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void firstCallExecutesSecondCallReplays() { |
||||||
|
AtomicInteger calls = new AtomicInteger(); |
||||||
|
|
||||||
|
WriteResult<String> first = guard.execute(MARK_SHIPPED, () -> { |
||||||
|
calls.incrementAndGet(); |
||||||
|
return "SHIP-1"; |
||||||
|
}, v -> v); |
||||||
|
|
||||||
|
WriteResult<String> second = guard.execute(MARK_SHIPPED, () -> { |
||||||
|
calls.incrementAndGet(); |
||||||
|
return "SHIP-2"; |
||||||
|
}, v -> v); |
||||||
|
|
||||||
|
assertEquals(WriteResult.Outcome.EXECUTED, first.outcome()); |
||||||
|
assertEquals("SHIP-1", first.resultRef()); |
||||||
|
assertEquals(WriteResult.Outcome.ALREADY_COMPLETED, second.outcome()); |
||||||
|
assertEquals("SHIP-1", second.resultRef()); |
||||||
|
assertNull(second.value()); |
||||||
|
assertEquals(1, calls.get(), "platform write must happen only once"); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void doubleKeysPersistedWithProviderAndRef() { |
||||||
|
guard.execute(MARK_SHIPPED, () -> "SHIP-1", v -> v); |
||||||
|
|
||||||
|
assertEquals(IdempotencyStatus.SUCCEEDED, |
||||||
|
store.get(MARK_SHIPPED.businessKey()).get().status()); |
||||||
|
assertEquals(IdempotencyStatus.SUCCEEDED, |
||||||
|
store.get(MARK_SHIPPED.providerKey()).get().status()); |
||||||
|
assertEquals(ChannelProvider.LINGXING, |
||||||
|
store.get(MARK_SHIPPED.businessKey()).get().provider()); |
||||||
|
assertTrue(MARK_SHIPPED.providerKey().startsWith("LINGXING:WALMART_SC:1108413237731:markShipped:")); |
||||||
|
assertTrue(MARK_SHIPPED.businessKey().startsWith("WALMART_SC:oms-wm-001:PO-1:pkg-1:")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void sameBusinessActionViaOtherProviderIsConflict() { |
||||||
|
guard.execute(MARK_SHIPPED, () -> "SHIP-1", v -> v); |
||||||
|
|
||||||
|
WriteScope viaDirect = WriteScope.of(ChannelProvider.DIRECT, Platform.WALMART_SC, "oms-wm-001", |
||||||
|
"wm-seller-01", "markShipped", "PO-1:pkg-1"); |
||||||
|
assertEquals(MARK_SHIPPED.businessKey(), viaDirect.businessKey()); |
||||||
|
|
||||||
|
CrossProviderConflictException ex = assertThrows(CrossProviderConflictException.class, |
||||||
|
() -> guard.execute(viaDirect, () -> "SHIP-2", v -> v)); |
||||||
|
assertEquals("LINGXING", ex.completedByProvider()); |
||||||
|
assertFalse(ex.retryable()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void concurrentAttemptRejectedWhileInProgress() { |
||||||
|
store.seedInProgress(MARK_SHIPPED.businessKey(), ChannelProvider.LINGXING, "worker-2", T0); |
||||||
|
|
||||||
|
IdempotencyConflictException ex = assertThrows(IdempotencyConflictException.class, |
||||||
|
() -> guard.execute(MARK_SHIPPED, () -> "SHIP-1", v -> v)); |
||||||
|
assertEquals(MARK_SHIPPED.businessKey(), ex.idempotencyKey()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void retryableFailureAllowsRerun() { |
||||||
|
ChannelException failure = ChannelException.builder() |
||||||
|
.message("http 503") |
||||||
|
.operation("markShipped") |
||||||
|
.retryable(true) |
||||||
|
.build(); |
||||||
|
|
||||||
|
assertThrows(ChannelException.class, () -> guard.<String>execute(MARK_SHIPPED, () -> { |
||||||
|
throw failure; |
||||||
|
}, v -> v)); |
||||||
|
|
||||||
|
assertEquals(IdempotencyStatus.FAILED_RETRYABLE, |
||||||
|
store.get(MARK_SHIPPED.businessKey()).get().status()); |
||||||
|
assertEquals(IdempotencyStatus.FAILED_RETRYABLE, |
||||||
|
store.get(MARK_SHIPPED.providerKey()).get().status()); |
||||||
|
|
||||||
|
WriteResult<String> retry = guard.execute(MARK_SHIPPED, () -> "SHIP-2", v -> v); |
||||||
|
assertEquals(WriteResult.Outcome.EXECUTED, retry.outcome()); |
||||||
|
assertEquals("SHIP-2", retry.resultRef()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void nonRetryableFailureBlocksAutomaticRetry() { |
||||||
|
ChannelException failure = ChannelException.builder() |
||||||
|
.message("http 400") |
||||||
|
.operation("markShipped") |
||||||
|
.retryable(false) |
||||||
|
.build(); |
||||||
|
|
||||||
|
assertThrows(ChannelException.class, () -> guard.<String>execute(MARK_SHIPPED, () -> { |
||||||
|
throw failure; |
||||||
|
}, v -> v)); |
||||||
|
|
||||||
|
assertEquals(IdempotencyStatus.FAILED_FINAL, |
||||||
|
store.get(MARK_SHIPPED.businessKey()).get().status()); |
||||||
|
|
||||||
|
ChannelException ex = assertThrows(ChannelException.class, |
||||||
|
() -> guard.execute(MARK_SHIPPED, () -> "SHIP-2", v -> v)); |
||||||
|
assertTrue(ex.getMessage().contains("manual intervention"), ex.getMessage()); |
||||||
|
assertFalse(ex.retryable()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void staleInProgressCanBeReclaimedAfterTtl() { |
||||||
|
store.seedInProgress(MARK_SHIPPED.businessKey(), ChannelProvider.LINGXING, "dead-worker", T0); |
||||||
|
clock.advance(Duration.ofSeconds(61)); |
||||||
|
|
||||||
|
WriteResult<String> result = guard.execute(MARK_SHIPPED, () -> "SHIP-1", v -> v); |
||||||
|
assertEquals(WriteResult.Outcome.EXECUTED, result.outcome()); |
||||||
|
assertEquals(IdempotencyStatus.SUCCEEDED, |
||||||
|
store.get(MARK_SHIPPED.businessKey()).get().status()); |
||||||
|
assertEquals("SHIP-1", store.get(MARK_SHIPPED.businessKey()).get().resultRef()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void providerKeyRecoversCrashWindowWithoutRewriting() { |
||||||
|
// 模拟:平台已写入、provider 键已记成功,但业务键没来得及写
|
||||||
|
store.seedSucceeded(MARK_SHIPPED.providerKey(), ChannelProvider.LINGXING, "SHIP-1", T0); |
||||||
|
AtomicInteger calls = new AtomicInteger(); |
||||||
|
|
||||||
|
WriteResult<String> result = guard.execute(MARK_SHIPPED, () -> { |
||||||
|
calls.incrementAndGet(); |
||||||
|
return "SHIP-2"; |
||||||
|
}, v -> v); |
||||||
|
|
||||||
|
assertEquals(WriteResult.Outcome.ALREADY_COMPLETED, result.outcome()); |
||||||
|
assertEquals("SHIP-1", result.resultRef()); |
||||||
|
assertEquals(0, calls.get(), "must not call platform again"); |
||||||
|
assertEquals(IdempotencyStatus.SUCCEEDED, |
||||||
|
store.get(MARK_SHIPPED.businessKey()).get().status()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void refundKeyMustNotUseAmount() { |
||||||
|
// 同一退款请求重复提交,金额格式变化不应产生新的业务动作
|
||||||
|
WriteScope a = WriteScope.of(ChannelProvider.DIRECT, Platform.WALMART_SC, "oms-wm-001", |
||||||
|
"wm-seller-01", "refund", "RET-1:ITEM-1:RFD-1"); |
||||||
|
WriteScope b = WriteScope.of(ChannelProvider.DIRECT, Platform.WALMART_SC, "oms-wm-001", |
||||||
|
"wm-seller-01", "refund", "RET-1:ITEM-1:RFD-1"); |
||||||
|
assertEquals(a.businessKey(), b.businessKey()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void guardOnlyWritesPlatformOnceAcrossRetry() { |
||||||
|
// 适配器层记录:平台写操作只应发生一次
|
||||||
|
common.ecommerce.testkit.FakeDirectAdapter adapter = |
||||||
|
common.ecommerce.testkit.FakeDirectAdapter.builder().build(); |
||||||
|
|
||||||
|
guard.execute(MARK_SHIPPED, () -> adapter.markShipped("pkg-1", "1Z-1"), v -> v); |
||||||
|
guard.execute(MARK_SHIPPED, () -> adapter.markShipped("pkg-1", "1Z-1"), v -> v); |
||||||
|
|
||||||
|
assertEquals(1, adapter.writeCallCount()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void blankScopePartsRejected() { |
||||||
|
assertThrows(IllegalArgumentException.class, () -> WriteScope.of(ChannelProvider.DIRECT, |
||||||
|
Platform.WALMART_SC, "oms-wm-001", "wm-seller-01", "markShipped", " ")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void statusLookupForOps() { |
||||||
|
assertFalse(guard.status(MARK_SHIPPED).isPresent()); |
||||||
|
guard.execute(MARK_SHIPPED, () -> "SHIP-1", v -> v); |
||||||
|
assertTrue(guard.status(MARK_SHIPPED).isPresent()); |
||||||
|
assertTrue(IdempotencyGuard.isRetryableStatus(IdempotencyStatus.FAILED_RETRYABLE)); |
||||||
|
} |
||||||
|
} |
||||||
Loading…
Reference in new issue