Browse Source
- Slf4jCallObserver 抽出 successLine / failedLine,日志渲染与绑定解耦 - 新增 Slf4jCallObserverTest、WriteAuditTest、RequestIdAndCoverageTestfeature/supplier-lingxing
4 changed files with 873 additions and 17 deletions
@ -0,0 +1,235 @@ |
|||||||
|
package common.ecommerce.audit; |
||||||
|
|
||||||
|
import common.ecommerce.error.ChannelException; |
||||||
|
import common.ecommerce.error.PlatformBusinessException; |
||||||
|
import common.ecommerce.model.ChannelProvider; |
||||||
|
import common.ecommerce.model.Platform; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.Instant; |
||||||
|
import java.time.ZoneId; |
||||||
|
import java.util.Arrays; |
||||||
|
import java.util.Collections; |
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** |
||||||
|
* {@link Slf4jCallObserver} 的日志契约:时区、时间格式、成功/失败字段、控制字符清洗与截断。 |
||||||
|
* |
||||||
|
* <p>断言的是包内可见的 {@code successLine} / {@code failedLine} 渲染结果, |
||||||
|
* 不依赖 classpath 上有哪个 SLF4J 绑定,也就不会因为宿主换日志实现而失效。</p> |
||||||
|
*/ |
||||||
|
class Slf4jCallObserverTest { |
||||||
|
|
||||||
|
private static final Instant AT = Instant.parse("2026-11-05T00:00:00Z"); |
||||||
|
|
||||||
|
// ------------------------------------------------------------ 时间显示
|
||||||
|
|
||||||
|
@Test |
||||||
|
void formatsTimeInConfiguredZone() { |
||||||
|
Slf4jCallObserver observer = new Slf4jCallObserver(ZoneId.of("Asia/Shanghai")); |
||||||
|
String line = observer.successLine(record(AT).build()); |
||||||
|
|
||||||
|
assertTrue(line.contains("at=2026-11-05 08:00:00"), line); |
||||||
|
assertFalse(line.contains("Z"), "日志不应出现 UTC 的 Z 后缀:" + line); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void formatsTimeInUtcWhenConfigured() { |
||||||
|
Slf4jCallObserver observer = new Slf4jCallObserver(ZoneId.of("UTC")); |
||||||
|
assertTrue(observer.successLine(record(AT).build()).contains("at=2026-11-05 00:00:00")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void formatsTimeWithCustomPatternIncludingMillisAndOffset() { |
||||||
|
Slf4jCallObserver observer = new Slf4jCallObserver(ZoneId.of("Asia/Shanghai"), |
||||||
|
"yyyy-MM-dd HH:mm:ss.SSSXXX"); |
||||||
|
assertEquals("yyyy-MM-dd HH:mm:ss.SSSXXX", observer.pattern()); |
||||||
|
assertEquals("2026-11-05 08:00:00.123+08:00", |
||||||
|
observer.format(AT.plusMillis(123))); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void zoneAndPatternAreExposedForStartupLog() { |
||||||
|
Slf4jCallObserver observer = new Slf4jCallObserver( |
||||||
|
ZoneId.of("America/Chicago"), "yyyy/MM/dd HH:mm"); |
||||||
|
assertEquals("America/Chicago", observer.zone().getId()); |
||||||
|
assertEquals("yyyy/MM/dd HH:mm", observer.pattern()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void nullArgumentsRejected() { |
||||||
|
assertThrows(NullPointerException.class, () -> new Slf4jCallObserver(null)); |
||||||
|
assertThrows(NullPointerException.class, () -> new Slf4jCallObserver(ZoneId.of("UTC"), null)); |
||||||
|
} |
||||||
|
|
||||||
|
// ------------------------------------------------------------ 成功 / 失败
|
||||||
|
|
||||||
|
@Test |
||||||
|
void successLineCarriesResultFields() { |
||||||
|
Slf4jCallObserver observer = new Slf4jCallObserver(ZoneId.of("UTC")); |
||||||
|
String line = observer.successLine(CallRecord.builder() |
||||||
|
.occurredAt(AT) |
||||||
|
.requestId("req-1") |
||||||
|
.provider(ChannelProvider.LINGXING) |
||||||
|
.platform(Platform.WALMART_SC) |
||||||
|
.omsStoreId("oms-wm-001") |
||||||
|
.externalStoreId("store-1") |
||||||
|
.operation("salesOrders.pull") |
||||||
|
.outcome(CallOutcome.SUCCESS) |
||||||
|
.durationMillis(42L) |
||||||
|
.resultCount(20) |
||||||
|
.failedCount(0) |
||||||
|
.params(Collections.<String, Object>singletonMap("pageSize", 20)) |
||||||
|
.build()); |
||||||
|
|
||||||
|
assertTrue(line.startsWith("sdk-call "), line); |
||||||
|
assertTrue(line.contains("op=salesOrders.pull"), line); |
||||||
|
assertTrue(line.contains("provider=LINGXING"), line); |
||||||
|
assertTrue(line.contains("platform=WALMART_SC"), line); |
||||||
|
assertTrue(line.contains("omsStoreId=oms-wm-001"), line); |
||||||
|
assertTrue(line.contains("storeId=store-1"), line); |
||||||
|
assertTrue(line.contains("requestId=req-1"), line); |
||||||
|
assertTrue(line.contains("cost=42ms"), line); |
||||||
|
assertTrue(line.contains("result=20"), line); |
||||||
|
assertTrue(line.contains("failed=0"), line); |
||||||
|
assertTrue(line.contains("pageSize=20"), line); |
||||||
|
assertFalse(line.contains("error="), "成功日志不应带 error:" + line); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void partialLineKeepsSuccessPrefixAndFailedCount() { |
||||||
|
Slf4jCallObserver observer = new Slf4jCallObserver(ZoneId.of("UTC")); |
||||||
|
String line = observer.successLine(CallRecord.builder() |
||||||
|
.occurredAt(AT) |
||||||
|
.operation("outbounds.review") |
||||||
|
.outcome(CallOutcome.PARTIAL) |
||||||
|
.resultCount(3) |
||||||
|
.failedCount(1) |
||||||
|
.build()); |
||||||
|
|
||||||
|
assertTrue(line.startsWith("sdk-call "), "PARTIAL 拿到了结果,按成功级别记录:" + line); |
||||||
|
assertTrue(line.contains("result=3"), line); |
||||||
|
assertTrue(line.contains("failed=1"), line); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void failedLineCarriesPlatformFields() { |
||||||
|
Slf4jCallObserver observer = new Slf4jCallObserver(ZoneId.of("UTC")); |
||||||
|
ChannelException error = ChannelException.builder() |
||||||
|
.message("请求过于频繁") |
||||||
|
.operation("salesOrders.pull") |
||||||
|
.platformCode("3001008") |
||||||
|
.platformRequestId("lx-req-1") |
||||||
|
.retryable(true) |
||||||
|
.build(); |
||||||
|
|
||||||
|
String line = observer.failedLine(CallRecord.builder() |
||||||
|
.occurredAt(AT) |
||||||
|
.requestId("req-1") |
||||||
|
.operation("salesOrders.pull") |
||||||
|
.outcome(CallOutcome.FAILURE) |
||||||
|
.error(error) |
||||||
|
.build()); |
||||||
|
|
||||||
|
assertTrue(line.startsWith("sdk-call-failed "), line); |
||||||
|
assertTrue(line.contains("requestId=req-1"), line); |
||||||
|
assertTrue(line.contains("retryable=true"), line); |
||||||
|
assertTrue(line.contains("platformCode=3001008"), line); |
||||||
|
assertTrue(line.contains("platformRequestId=lx-req-1"), line); |
||||||
|
assertTrue(line.contains("error=" + ChannelException.class.getName() + ": 请求过于频繁"), line); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void failedLineKeepsBusinessExceptionTypeAndCode() { |
||||||
|
Slf4jCallObserver observer = new Slf4jCallObserver(ZoneId.of("UTC")); |
||||||
|
PlatformBusinessException error = new PlatformBusinessException(ChannelException.builder() |
||||||
|
.message("shipment review failed for all orders, failNum=2") |
||||||
|
.operation("outbounds.review") |
||||||
|
.platformCode("3001008") |
||||||
|
.retryable(true)); |
||||||
|
|
||||||
|
String line = observer.failedLine(CallRecord.builder() |
||||||
|
.occurredAt(AT) |
||||||
|
.operation("outbounds.review") |
||||||
|
.outcome(CallOutcome.FAILURE) |
||||||
|
.error(error) |
||||||
|
.build()); |
||||||
|
|
||||||
|
assertTrue(line.contains("failNum=2"), line); |
||||||
|
assertTrue(line.contains("platformCode=3001008"), line); |
||||||
|
assertTrue(line.contains("error=" + PlatformBusinessException.class.getName()), line); |
||||||
|
} |
||||||
|
|
||||||
|
// ------------------------------------------------------------ 清洗与截断
|
||||||
|
|
||||||
|
@Test |
||||||
|
void controlCharactersAreStrippedIntoSingleLine() { |
||||||
|
Slf4jCallObserver observer = new Slf4jCallObserver(ZoneId.of("UTC")); |
||||||
|
ChannelException error = ChannelException.builder() |
||||||
|
.message("第一行\nFAKE LOG LINE\r\n第二行\t结束") |
||||||
|
.operation("salesOrders.pull") |
||||||
|
.build(); |
||||||
|
|
||||||
|
String line = observer.failedLine(CallRecord.builder() |
||||||
|
.occurredAt(AT) |
||||||
|
.operation("salesOrders.pull") |
||||||
|
.outcome(CallOutcome.FAILURE) |
||||||
|
.error(error) |
||||||
|
.build()); |
||||||
|
|
||||||
|
assertFalse(line.contains("\n"), "换行必须被替换,否则可伪造日志行:" + line); |
||||||
|
assertFalse(line.contains("\r"), line); |
||||||
|
assertFalse(line.contains("\t"), line); |
||||||
|
assertTrue(line.contains("第一行 FAKE LOG LINE"), line); |
||||||
|
assertTrue(line.contains("第二行 结束"), line); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void longMessageIsTruncated() { |
||||||
|
Slf4jCallObserver observer = new Slf4jCallObserver(ZoneId.of("UTC")); |
||||||
|
char[] filler = new char[2000]; |
||||||
|
Arrays.fill(filler, 'x'); |
||||||
|
ChannelException error = ChannelException.builder() |
||||||
|
.message(new String(filler)) |
||||||
|
.operation("salesOrders.pull") |
||||||
|
.build(); |
||||||
|
|
||||||
|
String line = observer.failedLine(CallRecord.builder() |
||||||
|
.occurredAt(AT) |
||||||
|
.operation("salesOrders.pull") |
||||||
|
.outcome(CallOutcome.FAILURE) |
||||||
|
.error(error) |
||||||
|
.build()); |
||||||
|
|
||||||
|
assertTrue(line.contains("..."), "超长文案应截断并标记"); |
||||||
|
assertFalse(line.contains(new String(filler)), "不应输出完整 2000 字符"); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void nullErrorMessageRendersAsNull() { |
||||||
|
Slf4jCallObserver observer = new Slf4jCallObserver(ZoneId.of("UTC")); |
||||||
|
String line = observer.failedLine(CallRecord.builder() |
||||||
|
.occurredAt(AT) |
||||||
|
.operation("writes.markShipped") |
||||||
|
.outcome(CallOutcome.FAILURE) |
||||||
|
.build()); |
||||||
|
|
||||||
|
assertTrue(line.contains("error=null: null"), line); |
||||||
|
} |
||||||
|
|
||||||
|
/** 一条成功记录的骨架,测试按需覆盖字段。 */ |
||||||
|
private static CallRecord.Builder record(Instant occurredAt) { |
||||||
|
return CallRecord.builder() |
||||||
|
.occurredAt(occurredAt) |
||||||
|
.provider(ChannelProvider.DIRECT) |
||||||
|
.platform(Platform.WALMART_SC) |
||||||
|
.operation("salesOrders.pull") |
||||||
|
.outcome(CallOutcome.SUCCESS) |
||||||
|
.resultCount(0) |
||||||
|
.failedCount(0); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,332 @@ |
|||||||
|
package common.ecommerce.idempotency; |
||||||
|
|
||||||
|
import common.ecommerce.audit.CallObserver; |
||||||
|
import common.ecommerce.audit.CallOutcome; |
||||||
|
import common.ecommerce.audit.CallRecord; |
||||||
|
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.IdempotencyClaim; |
||||||
|
import common.ecommerce.spi.IdempotencyRecord; |
||||||
|
import common.ecommerce.spi.IdempotencyStatus; |
||||||
|
import common.ecommerce.spi.IdempotencyStore; |
||||||
|
import org.junit.jupiter.api.BeforeEach; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
import java.time.Instant; |
||||||
|
import java.time.ZoneOffset; |
||||||
|
import java.util.ArrayList; |
||||||
|
import java.util.LinkedHashMap; |
||||||
|
import java.util.List; |
||||||
|
import java.util.Map; |
||||||
|
import java.util.Optional; |
||||||
|
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.assertNotNull; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** |
||||||
|
* 幂等层的审计:每一次裁决都要留一条 {@code writes.<action>} 记录。 |
||||||
|
* |
||||||
|
* <p>覆盖 EXECUTED、回放、崩溃窗口修复、并发冲突、终态失败、跨 provider 冲突、 |
||||||
|
* 可重试/不可重试失败八种场景。core 不依赖 testkit,这里自带一个最小内存 store。</p> |
||||||
|
*/ |
||||||
|
class WriteAuditTest { |
||||||
|
|
||||||
|
private static final Instant T0 = Instant.parse("2026-11-05T00:00:00Z"); |
||||||
|
private static final Clock CLOCK = Clock.fixed(T0, ZoneOffset.UTC); |
||||||
|
|
||||||
|
private static final WriteScope SCOPE = WriteScope.of( |
||||||
|
ChannelProvider.LINGXING, Platform.WALMART_SC, "oms-wm-001", "store-1", |
||||||
|
"markShipped", "PO-1:pkg-1"); |
||||||
|
|
||||||
|
private static final class CollectingObserver implements CallObserver { |
||||||
|
|
||||||
|
private final List<CallRecord> records = new ArrayList<CallRecord>(); |
||||||
|
|
||||||
|
@Override |
||||||
|
public void onCall(CallRecord record) { |
||||||
|
records.add(record); |
||||||
|
} |
||||||
|
|
||||||
|
CallRecord only() { |
||||||
|
assertEquals(1, records.size(), "每次写操作只应产生一条幂等层记录"); |
||||||
|
return records.get(0); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** 最小内存幂等存储:够覆盖守卫的全部分支。 */ |
||||||
|
private static final class MapStore implements IdempotencyStore { |
||||||
|
|
||||||
|
private final Map<String, IdempotencyRecord> records = new LinkedHashMap<String, IdempotencyRecord>(); |
||||||
|
|
||||||
|
@Override |
||||||
|
public IdempotencyClaim claim(String key, String owner, ChannelProvider provider, |
||||||
|
Instant now, long ttlSeconds) { |
||||||
|
IdempotencyRecord existing = records.get(key); |
||||||
|
if (existing != null) { |
||||||
|
if (existing.status() == IdempotencyStatus.SUCCEEDED) { |
||||||
|
return IdempotencyClaim.of(IdempotencyClaim.Outcome.SUCCEEDED, existing); |
||||||
|
} |
||||||
|
if (existing.status() == IdempotencyStatus.FAILED_FINAL) { |
||||||
|
return IdempotencyClaim.of(IdempotencyClaim.Outcome.FAILED_FINAL, existing); |
||||||
|
} |
||||||
|
if (existing.status() == IdempotencyStatus.IN_PROGRESS |
||||||
|
&& existing.updatedAt().plusSeconds(ttlSeconds).isAfter(now)) { |
||||||
|
return IdempotencyClaim.of(IdempotencyClaim.Outcome.IN_PROGRESS, existing); |
||||||
|
} |
||||||
|
} |
||||||
|
records.put(key, IdempotencyRecord.of(key, IdempotencyStatus.IN_PROGRESS, provider, |
||||||
|
owner, null, now)); |
||||||
|
return IdempotencyClaim.acquire(); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public void complete(String key, String owner, String resultRef, Instant now) { |
||||||
|
IdempotencyRecord current = records.get(key); |
||||||
|
records.put(key, IdempotencyRecord.of(key, IdempotencyStatus.SUCCEEDED, |
||||||
|
current.provider(), owner, resultRef, now)); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public void fail(String key, String owner, boolean retryable, Instant now) { |
||||||
|
IdempotencyRecord current = records.get(key); |
||||||
|
records.put(key, IdempotencyRecord.of(key, |
||||||
|
retryable ? IdempotencyStatus.FAILED_RETRYABLE : IdempotencyStatus.FAILED_FINAL, |
||||||
|
current.provider(), owner, null, now)); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public Optional<IdempotencyRecord> get(String key) { |
||||||
|
return Optional.ofNullable(records.get(key)); |
||||||
|
} |
||||||
|
|
||||||
|
void seedSucceeded(String key, ChannelProvider provider, String resultRef) { |
||||||
|
records.put(key, IdempotencyRecord.of(key, IdempotencyStatus.SUCCEEDED, provider, |
||||||
|
"other-worker", resultRef, T0)); |
||||||
|
} |
||||||
|
|
||||||
|
void seedInProgress(String key, ChannelProvider provider, String owner) { |
||||||
|
records.put(key, IdempotencyRecord.of(key, IdempotencyStatus.IN_PROGRESS, provider, |
||||||
|
owner, null, T0)); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
private MapStore store; |
||||||
|
private CollectingObserver observer; |
||||||
|
private IdempotencyGuard guard; |
||||||
|
|
||||||
|
@BeforeEach |
||||||
|
void setUp() { |
||||||
|
store = new MapStore(); |
||||||
|
observer = new CollectingObserver(); |
||||||
|
guard = new IdempotencyGuard(store, "worker-1", CLOCK, |
||||||
|
IdempotencyGuard.DEFAULT_CLAIM_TTL_SECONDS, observer); |
||||||
|
} |
||||||
|
|
||||||
|
// ------------------------------------------------------------ 成功路径
|
||||||
|
|
||||||
|
@Test |
||||||
|
void executedWriteIsRecorded() { |
||||||
|
WriteResult<String> result = guard.execute(SCOPE, () -> "SHIP-1", v -> v); |
||||||
|
|
||||||
|
assertEquals(WriteResult.Outcome.EXECUTED, result.outcome()); |
||||||
|
|
||||||
|
CallRecord record = observer.only(); |
||||||
|
assertEquals("writes.markShipped", record.operation(), "操作名要带 writes. 前缀"); |
||||||
|
assertEquals(CallOutcome.SUCCESS, record.outcome()); |
||||||
|
assertEquals(ChannelProvider.LINGXING, record.provider()); |
||||||
|
assertEquals(Platform.WALMART_SC, record.platform()); |
||||||
|
assertEquals("oms-wm-001", record.omsStoreId()); |
||||||
|
assertEquals(SCOPE.businessKey(), record.params().get("businessKey")); |
||||||
|
assertEquals(SCOPE.providerKey(), record.params().get("providerKey")); |
||||||
|
assertEquals("EXECUTED", record.params().get("stage")); |
||||||
|
assertEquals("SHIP-1", record.params().get("resultRef")); |
||||||
|
assertEquals(0, record.failedCount()); |
||||||
|
assertFalse(record.failed()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void replayIsRecordedAsSuccessWithStage() { |
||||||
|
guard.execute(SCOPE, () -> "SHIP-1", v -> v); |
||||||
|
WriteResult<String> replay = guard.execute(SCOPE, () -> "SHIP-2", v -> v); |
||||||
|
|
||||||
|
assertEquals(WriteResult.Outcome.ALREADY_COMPLETED, replay.outcome()); |
||||||
|
assertEquals("SHIP-1", replay.resultRef()); |
||||||
|
|
||||||
|
assertEquals(2, observer.records.size(), "首次执行与回放各一条"); |
||||||
|
CallRecord last = observer.records.get(1); |
||||||
|
assertEquals(CallOutcome.SUCCESS, last.outcome(), "回放不是失败"); |
||||||
|
assertEquals("ALREADY_COMPLETED", last.params().get("stage")); |
||||||
|
assertEquals("SHIP-1", last.params().get("resultRef")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void crashWindowRepairIsRecordedWithItsOwnStage() { |
||||||
|
// provider 键已成功、业务键没记上
|
||||||
|
store.seedSucceeded(SCOPE.providerKey(), ChannelProvider.LINGXING, "SHIP-9"); |
||||||
|
AtomicInteger calls = new AtomicInteger(); |
||||||
|
|
||||||
|
WriteResult<String> result = guard.execute(SCOPE, () -> { |
||||||
|
calls.incrementAndGet(); |
||||||
|
return "SHIP-NEW"; |
||||||
|
}, v -> v); |
||||||
|
|
||||||
|
assertEquals(WriteResult.Outcome.ALREADY_COMPLETED, result.outcome()); |
||||||
|
assertEquals("SHIP-9", result.resultRef()); |
||||||
|
assertEquals(0, calls.get(), "不得再次调用平台"); |
||||||
|
|
||||||
|
CallRecord record = observer.only(); |
||||||
|
assertEquals(CallOutcome.SUCCESS, record.outcome()); |
||||||
|
assertEquals("REPAIRED_FROM_PROVIDER_KEY", record.params().get("stage")); |
||||||
|
assertEquals("SHIP-9", record.params().get("resultRef")); |
||||||
|
} |
||||||
|
|
||||||
|
// ------------------------------------------------------------ 冲突与失败
|
||||||
|
|
||||||
|
@Test |
||||||
|
void inProgressConflictIsRecordedAsFailure() { |
||||||
|
store.seedInProgress(SCOPE.businessKey(), ChannelProvider.LINGXING, "worker-2"); |
||||||
|
|
||||||
|
assertThrows(IdempotencyConflictException.class, |
||||||
|
() -> guard.execute(SCOPE, () -> "SHIP-1", v -> v)); |
||||||
|
|
||||||
|
CallRecord record = observer.only(); |
||||||
|
assertEquals(CallOutcome.FAILURE, record.outcome()); |
||||||
|
assertEquals("IN_PROGRESS", record.params().get("stage")); |
||||||
|
assertEquals("worker-2", record.params().get("owner")); |
||||||
|
assertNotNull(record.errorType()); |
||||||
|
assertTrue(record.errorType().contains("IdempotencyConflictException"), record.errorType()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void failedFinalIsRecordedAsFailure() { |
||||||
|
ChannelException fatal = ChannelException.builder() |
||||||
|
.message("http 400") |
||||||
|
.operation("markShipped") |
||||||
|
.retryable(false) |
||||||
|
.build(); |
||||||
|
assertThrows(ChannelException.class, () -> guard.<String>execute(SCOPE, () -> { |
||||||
|
throw fatal; |
||||||
|
}, v -> v)); |
||||||
|
|
||||||
|
// 第二次:终态,守卫直接拒绝
|
||||||
|
ChannelException blocked = assertThrows(ChannelException.class, |
||||||
|
() -> guard.execute(SCOPE, () -> "SHIP-2", v -> v)); |
||||||
|
assertFalse(blocked.retryable()); |
||||||
|
|
||||||
|
assertEquals(2, observer.records.size()); |
||||||
|
CallRecord last = observer.records.get(1); |
||||||
|
assertEquals(CallOutcome.FAILURE, last.outcome()); |
||||||
|
assertEquals("FAILED_FINAL", last.params().get("stage")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void crossProviderConflictIsRecordedAsFailure() { |
||||||
|
guard.execute(SCOPE, () -> "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(SCOPE.businessKey(), viaDirect.businessKey()); |
||||||
|
|
||||||
|
assertThrows(CrossProviderConflictException.class, |
||||||
|
() -> guard.execute(viaDirect, () -> "SHIP-2", v -> v)); |
||||||
|
|
||||||
|
CallRecord last = observer.records.get(observer.records.size() - 1); |
||||||
|
assertEquals(CallOutcome.FAILURE, last.outcome()); |
||||||
|
assertEquals("CROSS_PROVIDER_CONFLICT", last.params().get("stage")); |
||||||
|
assertEquals("LINGXING", last.params().get("completedByProvider")); |
||||||
|
assertEquals(ChannelProvider.DIRECT, last.provider(), "记录的是本次请求的 provider"); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void retryableFailureIsRecordedAsFailureAndRerunSucceeds() { |
||||||
|
ChannelException failure = ChannelException.builder() |
||||||
|
.message("http 503") |
||||||
|
.operation("markShipped") |
||||||
|
.retryable(true) |
||||||
|
.build(); |
||||||
|
|
||||||
|
assertThrows(ChannelException.class, () -> guard.<String>execute(SCOPE, () -> { |
||||||
|
throw failure; |
||||||
|
}, v -> v)); |
||||||
|
|
||||||
|
CallRecord attempt = observer.only(); |
||||||
|
assertEquals(CallOutcome.FAILURE, attempt.outcome()); |
||||||
|
assertEquals("FAILED_RETRYABLE", attempt.params().get("stage")); |
||||||
|
assertEquals(Boolean.TRUE, attempt.params().get("retryable")); |
||||||
|
assertEquals(true, attempt.retryable()); |
||||||
|
|
||||||
|
WriteResult<String> retry = guard.execute(SCOPE, () -> "SHIP-2", v -> v); |
||||||
|
assertEquals(WriteResult.Outcome.EXECUTED, retry.outcome()); |
||||||
|
assertEquals(2, observer.records.size()); |
||||||
|
assertEquals(CallOutcome.SUCCESS, observer.records.get(1).outcome()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void nonRetryableFailureIsRecordedAsFinalFailure() { |
||||||
|
ChannelException failure = ChannelException.builder() |
||||||
|
.message("http 400") |
||||||
|
.operation("markShipped") |
||||||
|
.retryable(false) |
||||||
|
.build(); |
||||||
|
|
||||||
|
assertThrows(ChannelException.class, () -> guard.<String>execute(SCOPE, () -> { |
||||||
|
throw failure; |
||||||
|
}, v -> v)); |
||||||
|
|
||||||
|
CallRecord record = observer.only(); |
||||||
|
assertEquals(CallOutcome.FAILURE, record.outcome()); |
||||||
|
assertEquals("FAILED", record.params().get("stage")); |
||||||
|
assertEquals(Boolean.FALSE, record.params().get("retryable")); |
||||||
|
assertEquals(IdempotencyStatus.FAILED_FINAL, store.get(SCOPE.businessKey()).get().status()); |
||||||
|
} |
||||||
|
|
||||||
|
// ------------------------------------------------------------ 观察者与兼容性
|
||||||
|
|
||||||
|
@Test |
||||||
|
void observerFailureDoesNotBreakWrite() { |
||||||
|
CallObserver broken = new CallObserver() { |
||||||
|
@Override |
||||||
|
public void onCall(CallRecord record) { |
||||||
|
throw new IllegalStateException("observer down"); |
||||||
|
} |
||||||
|
}; |
||||||
|
IdempotencyGuard guarded = new IdempotencyGuard(store, "worker-1", CLOCK, |
||||||
|
IdempotencyGuard.DEFAULT_CLAIM_TTL_SECONDS, broken); |
||||||
|
|
||||||
|
WriteResult<String> result = guarded.execute(SCOPE, () -> "SHIP-1", v -> v); |
||||||
|
assertEquals(WriteResult.Outcome.EXECUTED, result.outcome(), "埋点失败不能影响写结果"); |
||||||
|
assertEquals(IdempotencyStatus.SUCCEEDED, store.get(SCOPE.businessKey()).get().status()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void guardWithoutObserverStillWorks() { |
||||||
|
IdempotencyGuard silent = new IdempotencyGuard(store, "worker-1", CLOCK, 60); |
||||||
|
assertEquals(WriteResult.Outcome.EXECUTED, |
||||||
|
silent.execute(SCOPE, () -> "SHIP-1", v -> v).outcome()); |
||||||
|
assertEquals(0, observer.records.size(), "没有注入观察者就不该产生记录"); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void operationNamePrefixesAction() { |
||||||
|
assertEquals("writes.markShipped", WriteAudit.operation(SCOPE)); |
||||||
|
assertEquals("writes.", WriteAudit.OPERATION_PREFIX); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void paramsCarryBothKeysAndStage() { |
||||||
|
Map<String, Object> params = WriteAudit.params(SCOPE, WriteAudit.Stage.EXECUTED, |
||||||
|
"resultRef", null); |
||||||
|
assertEquals(SCOPE.businessKey(), params.get("businessKey")); |
||||||
|
assertEquals(SCOPE.providerKey(), params.get("providerKey")); |
||||||
|
assertEquals("EXECUTED", params.get("stage")); |
||||||
|
assertTrue(params.containsKey("resultRef")); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,258 @@ |
|||||||
|
package common.ecommerce.sdk; |
||||||
|
|
||||||
|
import common.ecommerce.audit.CallObserver; |
||||||
|
import common.ecommerce.audit.CallOutcome; |
||||||
|
import common.ecommerce.audit.CallRecord; |
||||||
|
import common.ecommerce.audit.Slf4jCallObserver; |
||||||
|
import common.ecommerce.capability.CapabilityReport; |
||||||
|
import common.ecommerce.model.Capability; |
||||||
|
import common.ecommerce.model.ChannelProvider; |
||||||
|
import common.ecommerce.model.Platform; |
||||||
|
import common.ecommerce.model.account.AccountKey; |
||||||
|
import common.ecommerce.model.account.ChannelAccount; |
||||||
|
import common.ecommerce.model.order.SalesOrder; |
||||||
|
import common.ecommerce.model.order.SalesOrderQuery; |
||||||
|
import common.ecommerce.model.support.Page; |
||||||
|
import common.ecommerce.spi.ChannelSecret; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
import java.time.Instant; |
||||||
|
import java.time.ZoneId; |
||||||
|
import java.time.ZoneOffset; |
||||||
|
import java.util.ArrayList; |
||||||
|
import java.util.HashSet; |
||||||
|
import java.util.List; |
||||||
|
import java.util.Set; |
||||||
|
import java.util.concurrent.atomic.AtomicInteger; |
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** |
||||||
|
* 链路 ID 粒度与覆盖盲区:每次调用独立 requestId、可注入生成器、capabilities 埋点、启动日志。 |
||||||
|
*/ |
||||||
|
class RequestIdAndCoverageTest { |
||||||
|
|
||||||
|
private static final AccountKey KEY = |
||||||
|
AccountKey.of(ChannelProvider.DIRECT, Platform.WALMART_SC, "oms-wm-001"); |
||||||
|
|
||||||
|
private static final ChannelConnection CONNECTION = ChannelConnection.of( |
||||||
|
"https://api.example.com", |
||||||
|
ChannelSecret.builder().appKey("ak").appSecret("sk").build()); |
||||||
|
|
||||||
|
private static final Clock CLOCK = |
||||||
|
Clock.fixed(Instant.parse("2026-11-05T00:00:00Z"), ZoneOffset.UTC); |
||||||
|
|
||||||
|
private static final class CollectingObserver implements CallObserver { |
||||||
|
|
||||||
|
private final List<CallRecord> records = new ArrayList<CallRecord>(); |
||||||
|
|
||||||
|
@Override |
||||||
|
public void onCall(CallRecord record) { |
||||||
|
records.add(record); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
private static ChannelAccount account() { |
||||||
|
return ChannelAccount.builder() |
||||||
|
.key(KEY) |
||||||
|
.externalStoreId("wm-seller-01") |
||||||
|
.credentialRef("test") |
||||||
|
.marketplaceZone("America/Chicago") |
||||||
|
.currency("USD") |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
private static ChannelSdk.Builder builder(CallObserver observer) { |
||||||
|
return ChannelSdk.builder() |
||||||
|
.accountRepository(new ChannelSdkTest.FixedAccounts(account())) |
||||||
|
.clock(CLOCK) |
||||||
|
.register(new ChannelSdkTest.FakeDirectAdapter()) |
||||||
|
.callObserver(observer); |
||||||
|
} |
||||||
|
|
||||||
|
private static SalesOrderQuery query() { |
||||||
|
return SalesOrderQuery.builder().updatedAfter(Instant.EPOCH).build(); |
||||||
|
} |
||||||
|
|
||||||
|
// ------------------------------------------------------------ 每次调用独立 ID
|
||||||
|
|
||||||
|
@Test |
||||||
|
void everyFacadeViewGetsItsOwnRequestId() { |
||||||
|
CollectingObserver observer = new CollectingObserver(); |
||||||
|
ChannelSdk sdk = builder(observer).build(); |
||||||
|
|
||||||
|
sdk.salesOrders(KEY, CONNECTION).pull(query()); |
||||||
|
sdk.salesOrders(KEY, CONNECTION).pull(query()); |
||||||
|
|
||||||
|
assertEquals(2, observer.records.size()); |
||||||
|
String first = observer.records.get(0).requestId(); |
||||||
|
String second = observer.records.get(1).requestId(); |
||||||
|
assertNotNull(first); |
||||||
|
assertNotNull(second); |
||||||
|
assertNotEquals(first, second, "两次取视图必须各自拿到独立的 requestId"); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void cachedViewCanRefreshRequestIdPerCall() { |
||||||
|
CollectingObserver observer = new CollectingObserver(); |
||||||
|
ChannelSdk sdk = builder(observer).build(); |
||||||
|
|
||||||
|
// 宿主缓存门面对象时,同一个对象反复调用会共用取视图时的 ID
|
||||||
|
SalesOrdersFacadeHolder holder = new SalesOrdersFacadeHolder(); |
||||||
|
holder.view = sdk.salesOrders(KEY, CONNECTION); |
||||||
|
holder.view.pull(query()); |
||||||
|
String cached = observer.records.get(0).requestId(); |
||||||
|
holder.view.pull(query()); |
||||||
|
assertEquals(cached, observer.records.get(1).requestId(), |
||||||
|
"未刷新时就是共用同一个 ID,这是已知的取值范围"); |
||||||
|
|
||||||
|
// 用 withRequestId 显式换新 ID
|
||||||
|
AtomicInteger counter = new AtomicInteger(); |
||||||
|
holder.view.withRequestId("trace-" + counter.incrementAndGet()).pull(query()); |
||||||
|
holder.view.withRequestId("trace-" + counter.incrementAndGet()).pull(query()); |
||||||
|
|
||||||
|
Set<String> ids = new HashSet<String>(); |
||||||
|
for (CallRecord record : observer.records) { |
||||||
|
ids.add(record.requestId()); |
||||||
|
} |
||||||
|
assertEquals(4, ids.size(), "刷新后每条记录应有不同的 requestId"); |
||||||
|
assertTrue(ids.contains("trace-1")); |
||||||
|
assertTrue(ids.contains("trace-2")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void requestIdSupplierBridgesHostTraceId() { |
||||||
|
CollectingObserver observer = new CollectingObserver(); |
||||||
|
AtomicInteger counter = new AtomicInteger(); |
||||||
|
ChannelSdk sdk = builder(observer) |
||||||
|
.requestIdSupplier(() -> "trace-" + counter.incrementAndGet()) |
||||||
|
.build(); |
||||||
|
|
||||||
|
sdk.salesOrders(KEY, CONNECTION).pull(query()); |
||||||
|
sdk.salesOrders(KEY, CONNECTION).pull(query()); |
||||||
|
|
||||||
|
assertEquals("trace-1", observer.records.get(0).requestId()); |
||||||
|
assertEquals("trace-2", observer.records.get(1).requestId()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void blankRequestIdFailsFastInsteadOfSilentlyPassing() { |
||||||
|
ChannelSdk sdk = builder(new CollectingObserver()) |
||||||
|
.requestIdSupplier(() -> " ") |
||||||
|
.build(); |
||||||
|
|
||||||
|
IllegalStateException ex = assertThrows(IllegalStateException.class, |
||||||
|
() -> sdk.salesOrders(KEY, CONNECTION)); |
||||||
|
assertTrue(ex.getMessage().contains("requestIdSupplier"), ex.getMessage()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void contextWithRequestIdKeepsOtherFields() { |
||||||
|
ChannelContext ctx = ChannelContext.of(account(), CONNECTION, "req-1", CLOCK); |
||||||
|
ChannelContext copy = ctx.withRequestId("req-2"); |
||||||
|
|
||||||
|
assertEquals("req-2", copy.requestId()); |
||||||
|
assertEquals("req-1", ctx.requestId(), "原对象不变,避免缓存对象被串号"); |
||||||
|
assertEquals(KEY, copy.key()); |
||||||
|
assertEquals("wm-seller-01", copy.account().externalStoreId()); |
||||||
|
assertEquals("https://api.example.com", copy.endpointBaseUrl()); |
||||||
|
} |
||||||
|
|
||||||
|
// ------------------------------------------------------------ capabilities 埋点
|
||||||
|
|
||||||
|
@Test |
||||||
|
void capabilitiesIsNowObserved() { |
||||||
|
CollectingObserver observer = new CollectingObserver(); |
||||||
|
ChannelSdk sdk = builder(observer).build(); |
||||||
|
|
||||||
|
CapabilityReport report = sdk.capabilities(KEY); |
||||||
|
|
||||||
|
assertTrue(report.supports(Capability.SALES_ORDER)); |
||||||
|
assertEquals(1, observer.records.size(), "capabilities 也要留一条记录"); |
||||||
|
|
||||||
|
CallRecord record = observer.records.get(0); |
||||||
|
assertEquals("capabilities", record.operation()); |
||||||
|
assertEquals(CallOutcome.SUCCESS, record.outcome()); |
||||||
|
assertEquals(ChannelProvider.DIRECT, record.provider()); |
||||||
|
assertEquals(Platform.WALMART_SC, record.platform()); |
||||||
|
assertEquals("oms-wm-001", record.omsStoreId()); |
||||||
|
assertEquals("wm-seller-01", record.externalStoreId()); |
||||||
|
assertNotNull(record.requestId()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void missingAccountIsObservedAsFailureInsteadOfSilence() { |
||||||
|
CollectingObserver observer = new CollectingObserver(); |
||||||
|
ChannelSdk sdk = builder(observer).build(); |
||||||
|
|
||||||
|
AccountKey unknown = AccountKey.of(ChannelProvider.DIRECT, Platform.WALMART_SC, "oms-unknown"); |
||||||
|
assertThrows(IllegalStateException.class, () -> sdk.capabilities(unknown)); |
||||||
|
|
||||||
|
assertEquals(1, observer.records.size(), "账户没配好也要留痕,这是上线初期最常见的故障"); |
||||||
|
CallRecord record = observer.records.get(0); |
||||||
|
assertEquals("capabilities", record.operation()); |
||||||
|
assertEquals(CallOutcome.FAILURE, record.outcome()); |
||||||
|
assertEquals("oms-unknown", record.omsStoreId()); |
||||||
|
assertEquals(null, record.externalStoreId()); |
||||||
|
assertTrue(record.errorMessage().contains("not configured"), record.errorMessage()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void missingAdapterIsObservedAsFailure() { |
||||||
|
CollectingObserver observer = new CollectingObserver(); |
||||||
|
ChannelSdk sdk = builder(observer).build(); |
||||||
|
|
||||||
|
// 账户存在,但没有注册 LINGXING 的适配器
|
||||||
|
AccountKey lingxing = AccountKey.of(ChannelProvider.LINGXING, Platform.WALMART_SC, "oms-wm-001"); |
||||||
|
ChannelAccount lingxingAccount = ChannelAccount.builder() |
||||||
|
.key(lingxing) |
||||||
|
.externalStoreId("store-1") |
||||||
|
.credentialRef("test") |
||||||
|
.marketplaceZone("America/Chicago") |
||||||
|
.currency("USD") |
||||||
|
.build(); |
||||||
|
ChannelSdk withLingxingAccount = ChannelSdk.builder() |
||||||
|
.accountRepository(new ChannelSdkTest.FixedAccounts(lingxingAccount)) |
||||||
|
.clock(CLOCK) |
||||||
|
.register(new ChannelSdkTest.FakeDirectAdapter()) |
||||||
|
.callObserver(observer) |
||||||
|
.build(); |
||||||
|
|
||||||
|
assertThrows(IllegalStateException.class, () -> withLingxingAccount.capabilities(lingxing)); |
||||||
|
|
||||||
|
CallRecord record = observer.records.get(0); |
||||||
|
assertEquals(CallOutcome.FAILURE, record.outcome()); |
||||||
|
assertTrue(record.errorMessage().contains("no adapter registered"), record.errorMessage()); |
||||||
|
} |
||||||
|
|
||||||
|
// ------------------------------------------------------------ 启动日志
|
||||||
|
|
||||||
|
@Test |
||||||
|
void buildLogsStartupSummary() { |
||||||
|
// 启动日志走 Slf4jCallObserver 用同一个 logger 体系;这里只验证装配不报错、
|
||||||
|
// 且把 Slf4jCallObserver 作为观察者时 zone 能被识别
|
||||||
|
Slf4jCallObserver observer = new Slf4jCallObserver(ZoneId.of("Asia/Shanghai")); |
||||||
|
ChannelSdk sdk = builder(observer).build(); |
||||||
|
assertNotNull(sdk); |
||||||
|
assertEquals("Asia/Shanghai", observer.zone().getId()); |
||||||
|
} |
||||||
|
|
||||||
|
/** 只为了让「缓存门面对象」的写法更像宿主代码。 */ |
||||||
|
private static final class SalesOrdersFacadeHolder { |
||||||
|
|
||||||
|
private common.ecommerce.capability.SalesOrders view; |
||||||
|
} |
||||||
|
|
||||||
|
/** 冒烟:确认空页也能正常返回,避免上面用例受 FakeDirectAdapter 行为影响。 */ |
||||||
|
@Test |
||||||
|
void fakeAdapterReturnsEmptyPage() { |
||||||
|
ChannelSdk sdk = builder(new CollectingObserver()).build(); |
||||||
|
Page<SalesOrder> page = sdk.salesOrders(KEY, CONNECTION).pull(query()); |
||||||
|
assertEquals(0, page.size()); |
||||||
|
} |
||||||
|
} |
||||||
Loading…
Reference in new issue