From c6241dddc79b7ce0e7b27ba0d567518848e9a828 Mon Sep 17 00:00:00 2001 From: lml <1297555865@qq.com> Date: Mon, 9 Nov 2026 17:14:23 +0800 Subject: [PATCH] =?UTF-8?q?feat(xincang):=20=E6=96=B0=E5=A2=9E=E4=BF=A1?= =?UTF-8?q?=E4=BB=93=E4=B8=89=E6=96=B9=E4=BB=93=E6=A8=A1=E5=9D=97=E4=B8=8E?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E6=8D=A2=20token?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GET /api.login?appkey=&secret= 换取客户级 token,token 放 query 参数, 不是 Authorization 头 - token_expire_time 按北京时间 yyyy-MM-dd HH:mm:ss 解析为 UTC expiresAt; 字段缺失按文档 2 小时兜底,格式非法直接失败 - TokenManager 按 appkey 缓存(同客户多仓共用一个 token),提前 10 分钟续期; 信仓无 refresh 接口,到期即重新登录 - XincangEnvelope 统一校验顶层 errno 与 rst.code,HTTP 401/403/429/5xx 照常分类, trace_id 落到 platformRequestId - 本期不声明任何 WarehouseCapability,业务能力后续逐个接入 - 附登录只读探针,默认跳过,凭据走 -Dxincang.probe.* 待核对:生产基址(文档只给测试地址)与限流值(文档未公开,暂按 2 req/s)。 Co-Authored-By: Claude Code --- README.md | 30 +++- pom.xml | 6 + warehouse-sdk-xincang/pom.xml | 37 +++++ .../common/ecommerce/xincang/XincangConstants.java | 79 ++++++++++ .../ecommerce/xincang/adapter/XincangAdapter.java | 86 +++++++++++ .../xincang/adapter/XincangAdapterFactory.java | 51 +++++++ .../ecommerce/xincang/auth/XincangTokenClient.java | 130 ++++++++++++++++ .../common/ecommerce/xincang/dto/XincangDtos.java | 68 +++++++++ .../ecommerce/xincang/http/XincangEnvelope.java | 169 +++++++++++++++++++++ .../ecommerce/xincang/http/XincangRateLimiter.java | 57 +++++++ .../xincang/http/XincangRequestFactory.java | 114 ++++++++++++++ .../xincang/adapter/XincangAdapterTest.java | 124 +++++++++++++++ .../xincang/auth/XincangTokenClientTest.java | 153 +++++++++++++++++++ .../xincang/http/XincangRequestFactoryTest.java | 54 +++++++ .../xincang/probe/XincangLoginProbeTest.java | 103 +++++++++++++ 15 files changed, 1255 insertions(+), 6 deletions(-) create mode 100644 warehouse-sdk-xincang/pom.xml create mode 100644 warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/XincangConstants.java create mode 100644 warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapter.java create mode 100644 warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapterFactory.java create mode 100644 warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/auth/XincangTokenClient.java create mode 100644 warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/dto/XincangDtos.java create mode 100644 warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangEnvelope.java create mode 100644 warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangRateLimiter.java create mode 100644 warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangRequestFactory.java create mode 100644 warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/adapter/XincangAdapterTest.java create mode 100644 warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/auth/XincangTokenClientTest.java create mode 100644 warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/http/XincangRequestFactoryTest.java create mode 100644 warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/probe/XincangLoginProbeTest.java diff --git a/README.md b/README.md index abd9d98..3bf5b09 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ graph TD SHARED["sdk-common · 跨域共享层
异常 · 幂等 · 审计 · SPI · HTTP 传输 · Money/Page"] LX["lingxing · 领星聚合适配器"] YQN["warehouse-sdk-yqn · 运去哪适配器"] + XC["warehouse-sdk-xincang · 信仓适配器"] end EXT["领星开放平台 / 电商平台 / 三方仓"] @@ -58,8 +59,12 @@ graph TD YQN -. 实现能力接口 .-> WCAP YQN --> WMODEL YQN --> SHARED + XC -. 实现能力接口 .-> WCAP + XC --> WMODEL + XC --> SHARED IMPL -. 实现 SPI .-> SHARED YQN --> EXT + XC --> EXT ``` **模块依赖**(与各模块 `pom.xml` 一致,箭头指向被依赖方): @@ -73,6 +78,7 @@ graph BT whkit["warehouse-sdk-testkit"] lingxing["lingxing"] yqn["warehouse-sdk-yqn"] + xc["warehouse-sdk-xincang"] chcore --> common whcore --> common @@ -85,6 +91,8 @@ graph BT lingxing --> chcore yqn --> common yqn --> whcore + xc --> common + xc --> whcore ``` **一次商品查询的调用链**(订单、售后、出库等能力走同一条骨架): @@ -127,6 +135,7 @@ sequenceDiagram | `warehouse-sdk-testkit` | 仓库域测试替身:InMemory 仓仓库 / 落库 / 去重、FakeWarehouseAdapter | | `common-ecommerce-lingxing` | 领星聚合适配器(多子平台)。DTO 用 Lombok 生成访问器 | | `warehouse-sdk-yqn` | 运去哪三方仓适配器(P1 出库闭环,组织级固定 token 鉴权) | +| `warehouse-sdk-xincang` | 信仓三方仓适配器(本轮只落地登录换 token;能力位留空) | 依赖方向: ``` @@ -135,6 +144,7 @@ sdk-testkit ───────┼──→ sdk-common warehouse-sdk-core ┘ lingxing ───────────→ channel-sdk-core, sdk-common warehouse-sdk-yqn ──→ warehouse-sdk-core, sdk-common +warehouse-sdk-xincang ──→ warehouse-sdk-core, sdk-common ``` **渠道域与仓库域平级、互不依赖**,只在 `sdk-common` 上共享 SPI 契约与管道基础设施。 出库回传运单后由 OMS 调渠道域标发,仓库域不调用渠道域。 @@ -303,11 +313,18 @@ common.ecommerce │ └── sdk WarehouseSdk / WarehouseOperations / WarehouseOutbounds / │ WarehouseContext / WarehouseConnection / WarehouseWriteScope │ -└── yqn 运去哪三方仓(warehouse-sdk-yqn) - ├── YqnConstants 端点、路径、固定 token 请求头名、限流 - ├── adapter YqnAdapter(P1 出库) / YqnAdapterFactory / YqnOutboundMapper - ├── dto YqnDtos(字段级契约待打样核对) - └── http YqnRequestFactory / YqnEnvelope / YqnRateLimiter +├── yqn 运去哪三方仓(warehouse-sdk-yqn) +│ ├── YqnConstants 端点、路径、固定 token 请求头名、限流 +│ ├── adapter YqnAdapter(P1 出库) / YqnAdapterFactory / YqnOutboundMapper +│ ├── dto YqnDtos(字段级契约待打样核对) +│ └── http YqnRequestFactory / YqnEnvelope / YqnRateLimiter +│ +└── xincang 信仓三方仓(warehouse-sdk-xincang) + ├── XincangConstants 测试基址、登录路径、query 参数名、限流 + ├── auth XincangTokenClient(GET /api.login,无 refresh) + ├── adapter XincangAdapter(本轮仅登录) / XincangAdapterFactory + ├── dto XincangDtos.LoginResponse + └── http XincangRequestFactory / XincangEnvelope / XincangRateLimiter ``` 包名统一前缀 `common.ecommerce.`,下表省略前缀。 @@ -896,7 +913,8 @@ assertEquals(1, adapter.writeCallCount()); mvn test # 全部 mvn -pl lingxing test # 单模块 mvn -pl lingxing -Dtest=LingxingSdkListingCallTest test -mvn -pl warehouse-sdk-yqn test # 运去哪 P1 契约测试 +mvn -pl warehouse-sdk-yqn test # 运去哪 P1 契约测试 +mvn -pl warehouse-sdk-xincang -am test # 信仓登录 / 令牌缓存 ``` --- diff --git a/pom.xml b/pom.xml index 0bffe58..fce5317 100644 --- a/pom.xml +++ b/pom.xml @@ -33,6 +33,7 @@ warehouse-sdk-core warehouse-sdk-testkit warehouse-sdk-yqn + warehouse-sdk-xincang @@ -67,6 +68,11 @@ warehouse-sdk-yqn ${project.version} + + ecommerce + warehouse-sdk-xincang + ${project.version} + com.squareup.okhttp3 diff --git a/warehouse-sdk-xincang/pom.xml b/warehouse-sdk-xincang/pom.xml new file mode 100644 index 0000000..37b21bd --- /dev/null +++ b/warehouse-sdk-xincang/pom.xml @@ -0,0 +1,37 @@ + + + 4.0.0 + + + ecommerce + channel-sdk-parent + 1.0.0-SNAPSHOT + + + warehouse-sdk-xincang + 信仓三方仓适配器(3PL 仓储履约,登录换 token) + + + + ecommerce + sdk-common + + + ecommerce + warehouse-sdk-core + + + + ecommerce + sdk-testkit + test + + + org.junit.jupiter + junit-jupiter + test + + + diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/XincangConstants.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/XincangConstants.java new file mode 100644 index 0000000..b37c696 --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/XincangConstants.java @@ -0,0 +1,79 @@ +package common.ecommerce.xincang; + +import common.ecommerce.shared.support.PlatformTime; + +import java.time.ZoneId; + +/** + * 信仓(XinCang)协议常量。 + * + *

端点与路径是协议的一部分,写在代码里,不做成配置表。 + * 运行时不使用 {@link #TEST_BASE_URL}:端点由调用方每次经 + * {@code WarehouseConnection} 传入。

+ * + *

依据 Apifox「OMS接口文档V2」(2026-11 核对)与其《新 OMS 接口迁移调整说明》。

+ */ +public final class XincangConstants { + + /** 适配器标识。 */ + public static final String ADAPTER_ID = "xincang"; + + /** + * 测试 / 联调环境基址。 + * + *

文档明确写了这个地址;末尾不带斜杠,与 {@code WarehouseConnection} 的归一化一致, + * 路径直接以 {@code /} 开头拼接。

+ */ + public static final String TEST_BASE_URL = "http://test.api.oms.13u3.com/oms"; + + /** + * 生产环境基址。 + * + *

待核对:官方文档只给了测试地址(迁移说明里那句「生产环境接口路径与请求方法 + * 全部保持不变」只谈路径)。生产域名确认后只改这一处。调用方需要时可直接传自己的 + * {@code WarehouseConnection.endpointBaseUrl},不依赖本常量。

+ */ + public static final String PRODUCTION_BASE_URL = "待核对"; + + /** 登录换取 token。 */ + public static final String PATH_LOGIN = "/api.login"; + + /** 登录响应里的 token 归入哪个作用域;信仓用 query 参数传递,不是 {@code Authorization} 头。 */ + public static final String TOKEN_LOCATION = "query"; + + /** 业务接口 query 参数名(token 维度,客户级)。 */ + public static final String QUERY_TOKEN = "token"; + + /** 登录接口的 query 参数名。 */ + public static final String QUERY_APP_KEY = "appkey"; + /** 登录接口的 query 参数名。 */ + public static final String QUERY_APP_SECRET = "secret"; + + /** 业务成功:顶层 {@code errno=0} 且(列表类接口){@code rst.code="0"}。 */ + public static final String SUCCESS_ERRNO = "0"; + public static final String SUCCESS_RST_CODE = "0"; + + /** + * token 有效期兜底值(秒)。 + * + *

文档:测试数据说明写明有效期 2 小时;正常以响应里的 {@code token_expire_time} 为准, + * 只有该字段缺失 / 无法解析时才用这个值,并记一条 WARN 级别的日志语义。

+ */ + public static final long DEFAULT_TOKEN_TTL_SECONDS = 2 * 60 * 60L; + + /** 提前续期的窗口(秒)。 */ + public static final long TOKEN_EARLY_REFRESH_SECONDS = 600L; + + /** + * 限流:文档未公开限流值。 + * + *

待核对:按三家仓的保守默认 2 req/s/仓,联调确认后只改这一处。

+ */ + public static final int PERMITS_PER_SECOND = 2; + + /** 信仓以北京时间为准(文档「时间:北京时间」)。 */ + public static final ZoneId SYSTEM_ZONE = PlatformTime.BEIJING_ZONE; + + private XincangConstants() { + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapter.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapter.java new file mode 100644 index 0000000..809ae36 --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapter.java @@ -0,0 +1,86 @@ +package common.ecommerce.xincang.adapter; + +import common.ecommerce.http.HttpTransport; +import common.ecommerce.http.JsonCodec; +import common.ecommerce.http.TokenManager; +import common.ecommerce.shared.spi.AccessToken; +import common.ecommerce.shared.spi.ChannelSecret; +import common.ecommerce.shared.spi.LockProvider; +import common.ecommerce.shared.spi.TokenStore; +import common.ecommerce.warehouse.WarehouseCapability; +import common.ecommerce.warehouse.WarehouseProvider; +import common.ecommerce.warehouse.sdk.WarehouseAdapter; +import common.ecommerce.warehouse.sdk.WarehouseContext; +import common.ecommerce.xincang.XincangConstants; +import common.ecommerce.xincang.auth.XincangTokenClient; + +import java.time.Clock; +import java.util.EnumSet; + +/** + * 信仓适配器(本期只做登录换 token)。 + * + *

文档确认的鉴权方式:{@code GET /api.login?appkey=&secret=} 换取客户级 token, + * 有效期 2 小时、无 refresh 接口;业务请求把 token 放在 query 参数 {@code token} 里。 + * 本轮只落地登录与令牌缓存,出库 / 库存 / 预报等能力位一律不声明, + * 门面调用这些能力会显式抛 {@code WarehouseUnsupportedCapabilityException}。

+ * + *

适配器只持有协议与基础设施,不持有端点与凭据——两者随每次调用经 + * {@code WarehouseConnection} 传入。

+ */ +public final class XincangAdapter implements WarehouseAdapter { + + private final XincangTokenClient tokenClient; + private final TokenManager tokenManager; + + public XincangAdapter(HttpTransport transport, JsonCodec json, + TokenStore tokenStore, LockProvider lockProvider, Clock clock) { + this.tokenClient = new XincangTokenClient(transport, json, clock); + // 信仓 token 2h、无 refresh 接口:到期前 10 分钟重新登录换取; + // TokenManager 负责锁内防击穿与缓存读写,缓存键按 appkey(客户级)。 + this.tokenManager = new TokenManager(tokenStore, lockProvider, clock, + XincangConstants.TOKEN_EARLY_REFRESH_SECONDS) { + @Override + protected AccessToken refresh(ChannelSecret secret, AccessToken previous) { + return tokenClient.fetch(secret.endpointBaseUrl(), secret.appKey(), secret.appSecret()); + } + }; + } + + @Override + public String adapterId() { + return XincangConstants.ADAPTER_ID; + } + + @Override + public WarehouseProvider provider() { + return WarehouseProvider.XINCANG; + } + + /** 本期没有已实现的能力;后续接入业务接口时再逐个声明。 */ + @Override + public EnumSet capabilities() { + return EnumSet.noneOf(WarehouseCapability.class); + } + + /** + * 取一个可用 token(缓存命中则不登录)。 + * + *

供健康检查与联调探针使用;业务方法接入时也应经此取 token, + * 不要在适配器外自行缓存。

+ * + * @throws common.ecommerce.shared.error.AuthException 登录被拒或令牌结构不符合文档 + */ + public AccessToken login(WarehouseContext ctx) { + return tokenManager.getOrRefresh(tokenKey(ctx.secret()), ctx.secret()); + } + + /** + * 令牌缓存维度:信仓 token 按客户(appkey)发放,同一 appkey 下多仓共用一个 token。 + * + *

用 appkey 而不是 {@code warehouseCode},避免同客户多仓重复登录。

+ */ + static String tokenKey(ChannelSecret secret) { + return XincangConstants.ADAPTER_ID + ":" + secret.appKey(); + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapterFactory.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapterFactory.java new file mode 100644 index 0000000..d884817 --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapterFactory.java @@ -0,0 +1,51 @@ +package common.ecommerce.xincang.adapter; + +import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.http.OkHttpTransport; +import common.ecommerce.shared.spi.LockProvider; +import common.ecommerce.shared.spi.TokenStore; +import common.ecommerce.warehouse.WarehouseProvider; +import common.ecommerce.warehouse.sdk.WarehouseAdapter; +import common.ecommerce.warehouse.sdk.WarehouseAdapterFactory; +import common.ecommerce.xincang.XincangConstants; + +import java.time.Clock; + +/** + * 信仓适配器工厂。 + * + *

与领星适配器同构:令牌存储与锁由宿主注入,端点与凭据仍随每次调用传入。

+ */ +public final class XincangAdapterFactory implements WarehouseAdapterFactory { + + private final TokenStore tokenStore; + private final LockProvider lockProvider; + private final Clock clock; + + public XincangAdapterFactory(TokenStore tokenStore, LockProvider lockProvider, Clock clock) { + this.tokenStore = tokenStore; + this.lockProvider = lockProvider; + this.clock = clock; + } + + @Override + public String adapterId() { + return XincangConstants.ADAPTER_ID; + } + + @Override + public WarehouseProvider provider() { + return WarehouseProvider.XINCANG; + } + + /** + * 端点与凭据由调用方在每次请求时传入,工厂只装配协议与基础设施。 + */ + @Override + public WarehouseAdapter create(AdapterConfig config) { + return new XincangAdapter( + new OkHttpTransport("common-ecommerce/1.0.0 (xincang)"), + new JacksonJsonCodec(), + tokenStore, lockProvider, clock); + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/auth/XincangTokenClient.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/auth/XincangTokenClient.java new file mode 100644 index 0000000..675d0a2 --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/auth/XincangTokenClient.java @@ -0,0 +1,130 @@ +package common.ecommerce.xincang.auth; + +import common.ecommerce.http.HttpRequest; +import common.ecommerce.http.HttpResponse; +import common.ecommerce.http.HttpTransport; +import common.ecommerce.http.JsonCodec; +import common.ecommerce.shared.error.ValidationException; +import common.ecommerce.shared.spi.AccessToken; +import common.ecommerce.warehouse.error.WarehouseException; +import common.ecommerce.xincang.XincangConstants; +import common.ecommerce.xincang.dto.XincangDtos; +import common.ecommerce.xincang.http.XincangEnvelope; +import common.ecommerce.xincang.http.XincangRateLimiter; +import common.ecommerce.xincang.http.XincangRequestFactory; + +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * 信仓登录接口({@code GET /api.login})。 + * + *

文档(Apifox「OMS接口文档V2」)确认:query 参数 {@code appkey} / {@code secret}, + * 响应 {@code rst} 直接给出 {@code token} 与 {@code token_expire_time}(北京时间 + * {@code yyyy-MM-dd HH:mm:ss}),有效期 2 小时。没有 refresh 接口,过期只能重新登录; + * 续期由 {@code TokenManager} 提前刷新完成。

+ * + *

token 是客户级(同一 appkey 下多仓共用),后续业务请求把它放在 query 参数 + * {@code token} 里,不是 {@code Authorization} 头。

+ */ +public final class XincangTokenClient { + + private static final String OP_FETCH = "token.fetch"; + + /** 文档给的时间格式,按北京时间解释。 */ + private static final DateTimeFormatter EXPIRE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private final HttpTransport transport; + private final JsonCodec json; + private final XincangRequestFactory requestFactory; + private final XincangRateLimiter rateLimiter; + private final Clock clock; + + public XincangTokenClient(HttpTransport transport, JsonCodec json, Clock clock) { + this(transport, json, clock, new XincangRateLimiter()); + } + + public XincangTokenClient(HttpTransport transport, JsonCodec json, Clock clock, + XincangRateLimiter rateLimiter) { + this.transport = transport; + this.json = json; + this.clock = clock; + this.requestFactory = new XincangRequestFactory(json); + this.rateLimiter = rateLimiter; + } + + /** + * 登录换取令牌。端点由调用方每次传入,与其它接口一致。 + * + * @param baseUrl 本次调用的基址({@code WarehouseConnection.endpointBaseUrl()}) + * @param appKey 登录 appkey + * @param appSecret 登录 secret + * @return 令牌;{@code expiresAt} 已按响应里的 {@code token_expire_time} 折算成 UTC + */ + public AccessToken fetch(String baseUrl, String appKey, String appSecret) { + rateLimiter.acquire(XincangConstants.PATH_LOGIN, XincangConstants.PERMITS_PER_SECOND); + HttpRequest req = requestFactory.login(baseUrl, appKey, appSecret, OP_FETCH); + HttpResponse resp = transport.execute(req); + + XincangEnvelope envelope = XincangEnvelope.of(resp, json, OP_FETCH, null); + XincangDtos.LoginResponse login = json.fromJson(envelope.body(), XincangDtos.LoginResponse.class); + XincangDtos.LoginResult result = login == null ? null : login.rst; + + String token = result == null ? null : result.token; + if (token == null || token.trim().isEmpty()) { + throw validation(envelope.platformTraceId(), "xincang login response has no rst.token", + envelope.body()); + } + + return AccessToken.builder() + .value(token.trim()) + .expiresAt(expiresAt(result.tokenExpireTime, envelope)) + .build(); + } + + /** + * 过期时刻。 + * + *

字段缺失 / 空白时按文档写明的 2 小时兜底;字段存在但格式不对则直接失败—— + * 那说明报文和文档不一致,静默兜底会把续期时间算错。

+ */ + private Instant expiresAt(String raw, XincangEnvelope envelope) { + if (raw == null || raw.trim().isEmpty()) { + return Instant.now(clock).plusSeconds(XincangConstants.DEFAULT_TOKEN_TTL_SECONDS); + } + try { + LocalDateTime local = LocalDateTime.parse(raw.trim(), EXPIRE_FORMAT); + return local.atZone(XincangConstants.SYSTEM_ZONE).toInstant(); + } catch (DateTimeParseException e) { + // ChannelException.Builder.build() 只返回 ChannelException,没有 build(cause) 重载; + // 解析失败本身不带嵌套异常,靠 message 说明原因即可 + throw validation(envelope.platformTraceId(), + "xincang token_expire_time is not yyyy-MM-dd HH:mm:ss: " + raw, envelope.body()); + } + } + + private static ValidationException validation(String traceId, String message, String body) { + return new ValidationException(base(traceId) + .message(message) + .rawResponse(truncate(body))); + } + + private static WarehouseException.Builder base(String traceId) { + return WarehouseException.builder() + .operation(OP_FETCH) + .provider(XincangConstants.ADAPTER_ID) + .platformRequestId(traceId) + .retryable(false); + } + + private static String truncate(String body) { + if (body == null) { + return null; + } + // 登录响应含 token 与 api_client_secret,异常里只留很短一段便于定位于字段层面 + return body.length() <= 300 ? body : body.substring(0, 300) + "..."; + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/dto/XincangDtos.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/dto/XincangDtos.java new file mode 100644 index 0000000..4333d81 --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/dto/XincangDtos.java @@ -0,0 +1,68 @@ +package common.ecommerce.xincang.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * 信仓报文结构。 + * + *

字段名以 Apifox「OMS接口文档V2」为准。信仓全局响应外层统一为 + * {@code {"rst": ..., "errno": 0, "err": "", "trace_id": "..."}},这里只放登录接口用到的部分。 + * 字段差异只改本类,不动适配器与领域模型。

+ */ +public final class XincangDtos { + + private XincangDtos() { + } + + /** + * 登录响应({@code GET /api.login})。 + * + *

注意与业务接口不同:登录的 {@code rst} 没有 {@code code/msg/data} 包裹, + * 而是直接给出客户与 token 字段。

+ */ + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class LoginResponse { + + /** 登录结果;业务失败时可能为 null。 */ + @JsonProperty("rst") + public LoginResult rst; + + /** 0 表示成功。 */ + @JsonProperty("errno") + public Integer errno; + + /** 错误描述;成功时为空串。 */ + @JsonProperty("err") + public String err; + + /** 信仓侧链路号。 */ + @JsonProperty("trace_id") + public String traceId; + } + + /** 登录结果的 {@code rst} 部分。 */ + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class LoginResult { + + /** 客户 id。 */ + @JsonProperty("id") + public String customerId; + + /** 回显的 APIKEY,正常等于登录用的 appkey。 */ + @JsonProperty("api_client_id") + public String apiClientId; + + /** 回显的 APISECRET;不需要也不应落盘,仅用于排障时核对身份。 */ + @JsonProperty("api_client_secret") + public String apiClientSecret; + + /** 过期时间,北京时间 {@code yyyy-MM-dd HH:mm:ss}。 */ + @JsonProperty("token_expire_time") + public String tokenExpireTime; + + /** 令牌本体(形如 {@code {D0A7A4FB-...}})。 */ + @JsonProperty("token") + public String token; + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangEnvelope.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangEnvelope.java new file mode 100644 index 0000000..87c7d1d --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangEnvelope.java @@ -0,0 +1,169 @@ +package common.ecommerce.xincang.http; + +import common.ecommerce.http.HttpResponse; +import common.ecommerce.http.JsonCodec; +import common.ecommerce.shared.error.AuthException; +import common.ecommerce.shared.error.ChannelException; +import common.ecommerce.shared.error.PlatformBusinessException; +import common.ecommerce.shared.error.RateLimitException; +import common.ecommerce.shared.error.TransientException; +import common.ecommerce.shared.error.ValidationException; +import common.ecommerce.xincang.XincangConstants; + +/** + * 信仓响应信封校验。 + * + *

信仓统一外层(Apifox「OMS接口文档V2」):

+ *
+ * { "rst": ..., "errno": 0, "err": "", "trace_id": "..." }
+ * 
+ * + *

两条成功判定:顶层 {@code errno} 为 0;业务接口的 {@code rst} 是 + * {@code {"code":"0","msg":"","data":...}} 时还要求 {@code rst.code} 为 {@code "0"}。 + * 登录是例外——它的 {@code rst} 直接是客户 / token 字段,没有 {@code code},缺失即视为通过。

+ * + *

HTTP 401/403/429/5xx 仍按 HTTP 语义映射:网关或代理层直接拒绝时也要能正确分类。

+ */ +public final class XincangEnvelope { + + /** 原始响应体。 */ + private final String rawBody; + /** 信仓侧链路号 {@code trace_id};可能为 null。 */ + private final String platformTraceId; + + private XincangEnvelope(String rawBody, String platformTraceId) { + this.rawBody = rawBody; + this.platformTraceId = platformTraceId; + } + + /** + * 校验 HTTP 状态与业务码。 + * + * @param response 传输层响应 + * @param json 用于读 {@code errno} / {@code rst.code} / {@code trace_id} + * @param operation 门面操作名,如 {@code token.fetch} + * @param requestId 我方链路 ID + * @throws AuthException 401 / 403 + * @throws RateLimitException 429 + * @throws TransientException 5xx + * @throws ValidationException 其它非 2xx,或报文结构不符合预期 + * @throws PlatformBusinessException errno 非 0,或 rst.code 非 0 + */ + public static XincangEnvelope of(HttpResponse response, JsonCodec json, String operation, + String requestId) { + int status = response.statusCode(); + if (status == 401 || status == 403) { + throw new AuthException(base(operation, requestId) + .message("xincang auth failed: http " + status) + .platformCode(String.valueOf(status)) + .rawResponse(truncate(response.body())) + .retryable(false)); + } + if (status == 429) { + throw new RateLimitException(base(operation, requestId) + .message("xincang rate limited") + .platformCode(String.valueOf(status)) + .retryable(true), retryAfterMillis(response)); + } + if (status >= 500) { + throw new TransientException(base(operation, requestId) + .message("xincang server error: http " + status) + .platformCode(String.valueOf(status)) + .retryable(true), null); + } + if (status < 200 || status >= 300) { + throw new ValidationException(base(operation, requestId) + .message("xincang request rejected: http " + status) + .platformCode(String.valueOf(status)) + .rawResponse(truncate(response.body())) + .retryable(false)); + } + + String body = response.body(); + if (body == null || body.trim().isEmpty()) { + throw new ValidationException(base(operation, requestId) + .message("xincang returned an empty body") + .retryable(false)); + } + + String traceId = json.stringAt(body, "trace_id"); + String errno = json.stringAt(body, "errno"); + if (errno == null || errno.trim().isEmpty()) { + throw new ValidationException(base(operation, requestId) + .message("xincang response has no errno") + .platformRequestId(traceId) + .rawResponse(truncate(body)) + .retryable(false)); + } + if (!XincangConstants.SUCCESS_ERRNO.equals(errno.trim())) { + throw new PlatformBusinessException(base(operation, requestId) + .message("xincang business error: errno=" + errno + + ", err=" + json.stringAt(body, "err")) + .platformCode(errno.trim()) + .platformRequestId(traceId) + .rawResponse(truncate(body)) + .retryable(false)); + } + + String rstCode = json.stringAt(body, "rst.code"); + if (rstCode != null && !XincangConstants.SUCCESS_RST_CODE.equals(rstCode.trim())) { + throw new PlatformBusinessException(base(operation, requestId) + .message("xincang business error: rst.code=" + rstCode + + ", rst.msg=" + json.stringAt(body, "rst.msg")) + .platformCode(rstCode.trim()) + .platformRequestId(traceId) + .rawResponse(truncate(body)) + .retryable(false)); + } + return new XincangEnvelope(body, traceId); + } + + /** 原始响应体;不会是 null。 */ + public String body() { + return rawBody; + } + + /** 信仓侧链路号 {@code trace_id};可能为 null。 */ + public String platformTraceId() { + return platformTraceId; + } + + /** + * 统一异常字段。 + * + *

返回 {@link ChannelException.Builder} 而不是 {@code WarehouseException.Builder}: + * 仓库域的自定义异常仅有 {@code WarehouseException} 一个,其余分类(Auth / RateLimit / + * Transient / Validation / PlatformBusiness)的构造器都收 {@code ChannelException.Builder}。

+ * + *

{@code warehouseCode} 保留在签名里便于调用方一致传参,但 不写进 + * {@code omsStoreId}——那是渠道域的店铺 ID,填仓编码会污染审计字段。 + * 需要仓维度的错误请由适配器层包一层 {@code WarehouseException}。

+ */ + private static ChannelException.Builder base(String operation, + String requestId) { + return ChannelException.builder() + .operation(operation) + .provider(XincangConstants.ADAPTER_ID) + .requestId(requestId); + } + + /** {@code Retry-After} 秒折算毫秒;缺失按 1s。 */ + private static long retryAfterMillis(HttpResponse response) { + String header = response.header("Retry-After"); + if (header == null || header.trim().isEmpty()) { + return 1000L; + } + try { + return Math.max(0L, Long.parseLong(header.trim()) * 1000L); + } catch (NumberFormatException e) { + return 1000L; + } + } + + private static String truncate(String body) { + if (body == null) { + return null; + } + return body.length() <= 2000 ? body : body.substring(0, 2000) + "..."; + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangRateLimiter.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangRateLimiter.java new file mode 100644 index 0000000..64fa4bf --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangRateLimiter.java @@ -0,0 +1,57 @@ +package common.ecommerce.xincang.http; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.LongSupplier; + +/** + * 按接口路径的令牌桶。 + * + *

信仓文档未公开限流值,先按保守默认 {@code XincangConstants.PERMITS_PER_SECOND} 节流; + * 429 的 {@code Retry-After} 由宿主处理,这里只做本地限速。

+ * + *

进程内实现,多实例部署会叠加;需要跨实例限流时由宿主替换。 + * 与领星限流器同构,可注入 {@link Sleeper} 与纳秒时钟,便于测试。

+ */ +public final class XincangRateLimiter { + + /** 便于测试注入,生产用 {@link Thread#sleep}。 */ + public interface Sleeper { + void sleep(long millis, int nanos); + } + + private final Map nextAllowed = new HashMap<>(); + private final Sleeper sleeper; + private final LongSupplier nanoClock; + + public XincangRateLimiter() { + this((millis, nanos) -> { + try { + Thread.sleep(millis, nanos); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }, System::nanoTime); + } + + public XincangRateLimiter(Sleeper sleeper, LongSupplier nanoClock) { + this.sleeper = sleeper; + this.nanoClock = nanoClock; + } + + /** 同一路径两次调用之间至少间隔 {@code 1e9 / permitsPerSecond} 纳秒。 */ + public synchronized void acquire(String path, int permitsPerSecond) { + if (permitsPerSecond <= 0) { + return; + } + long interval = 1_000_000_000L / permitsPerSecond; + long now = nanoClock.getAsLong(); + Long next = nextAllowed.get(path); + if (next != null && now < next) { + long wait = next - now; + sleeper.sleep(wait / 1_000_000L, (int) (wait % 1_000_000L)); + now = nanoClock.getAsLong(); + } + nextAllowed.put(path, now + interval); + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangRequestFactory.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangRequestFactory.java new file mode 100644 index 0000000..8b92c6e --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangRequestFactory.java @@ -0,0 +1,114 @@ +package common.ecommerce.xincang.http; + +import common.ecommerce.http.HttpRequest; +import common.ecommerce.http.JsonCodec; +import common.ecommerce.shared.spi.ChannelSecret; +import common.ecommerce.xincang.XincangConstants; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * 构造信仓请求。 + * + *

鉴权是「登录换 token + 每次业务请求带 query 参数 {@code token}」(文档对所有业务接口 + * 都把 {@code token} 列为必填 query 参数),因此不走 {@code Authorization} 头。 + * 凭据复用 {@link ChannelSecret#appKey()} / {@link ChannelSecret#appSecret()}。

+ */ +public final class XincangRequestFactory { + + private final JsonCodec json; + + public XincangRequestFactory(JsonCodec json) { + this.json = json; + } + + /** 登录:{@code GET /api.login?appkey=&secret=}。 */ + public HttpRequest login(String baseUrl, String appKey, String appSecret, String operation) { + Map query = new LinkedHashMap<>(); + query.put(XincangConstants.QUERY_APP_KEY, requireText(appKey, + "xincang requires ChannelSecret.appKey()")); + query.put(XincangConstants.QUERY_APP_SECRET, requireText(appSecret, + "xincang requires ChannelSecret.appSecret()")); + return get(baseUrl, XincangConstants.PATH_LOGIN, query, operation); + } + + /** GET:业务参数全部放 query。 */ + public HttpRequest get(String baseUrl, String path, Map params, String operation) { + StringBuilder url = new StringBuilder(trimTrailingSlash(baseUrl)).append(path); + if (params != null && !params.isEmpty()) { + url.append('?'); + boolean first = true; + for (Map.Entry e : params.entrySet()) { + if (e.getValue() == null) { + continue; + } + if (!first) { + url.append('&'); + } + url.append(urlEncode(e.getKey())).append('=').append(urlEncode(stringify(e.getValue()))); + first = false; + } + } + return HttpRequest.builder() + .method("GET") + .url(url.toString()) + .operation(operation) + .build(); + } + + /** + * 业务 GET:在 {@code params} 上补 {@code token}。 + * + *

后续接口(订单 / 库存 / 预报)都要求 token 作为 query 参数,这个方法集中处理, + * 免得各 Source 各写一遍。本轮只落地登录,接入业务接口时直接复用。

+ */ + public HttpRequest getWithToken(String baseUrl, String path, Map params, + String token, String operation) { + Map query = new LinkedHashMap<>(); + if (params != null) { + query.putAll(params); + } + query.put(XincangConstants.QUERY_TOKEN, requireText(token, + "xincang requires a token; call login first")); + return get(baseUrl, path, query, operation); + } + + /** 集合 / 对象按 JSON 序列化,其余按字符串。 */ + private String stringify(Object value) { + if (value instanceof Collection || value instanceof Map) { + return json.toJson(value); + } + return String.valueOf(value); + } + + private static String requireText(String value, String message) { + if (value == null || value.trim().isEmpty()) { + throw new IllegalStateException(message); + } + return value.trim(); + } + + private static String trimTrailingSlash(String url) { + if (url == null || url.trim().isEmpty()) { + throw new IllegalStateException("xincang endpointBaseUrl must not be blank"); + } + String trimmed = url.trim(); + int end = trimmed.length(); + while (end > 0 && trimmed.charAt(end - 1) == '/') { + end--; + } + return trimmed.substring(0, end); + } + + private static String urlEncode(String v) { + try { + return URLEncoder.encode(v == null ? "" : v, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/adapter/XincangAdapterTest.java b/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/adapter/XincangAdapterTest.java new file mode 100644 index 0000000..47edd41 --- /dev/null +++ b/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/adapter/XincangAdapterTest.java @@ -0,0 +1,124 @@ +package common.ecommerce.xincang.adapter; + +import common.ecommerce.shared.spi.ChannelSecret; +import common.ecommerce.shared.testkit.InMemoryLockProvider; +import common.ecommerce.shared.testkit.InMemoryTokenStore; +import common.ecommerce.shared.testkit.MutableClock; +import common.ecommerce.shared.testkit.RecordingTransport; +import common.ecommerce.shared.testkit.Responses; +import common.ecommerce.warehouse.WarehouseCapability; +import common.ecommerce.warehouse.WarehouseProvider; +import common.ecommerce.warehouse.sdk.WarehouseConnection; +import common.ecommerce.warehouse.sdk.WarehouseContext; +import common.ecommerce.xincang.XincangConstants; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * 信仓适配器令牌缓存:登录只发一次、到期前提前续期、按 appkey 隔离缓存。 + */ +class XincangAdapterTest { + + private static final String BASE = XincangConstants.TEST_BASE_URL; + private static final String APP_KEY = "ak-1"; + + private RecordingTransport transport; + private InMemoryTokenStore tokens; + private InMemoryLockProvider locks; + private MutableClock clock; + + @BeforeEach + void setUp() { + transport = RecordingTransport.create(); + tokens = new InMemoryTokenStore(); + locks = new InMemoryLockProvider(); + clock = MutableClock.atUtc("2026-11-09T00:00:00Z"); + } + + /** 每次登录都返回一个新 token,并给 2 小时有效期(北京时间)。 */ + private XincangAdapter adapter() { + int[] sequence = {0}; + transport.route(XincangConstants.PATH_LOGIN, req -> { + sequence[0]++; + return Responses.ok("{\"rst\":{\"id\":\"c-1\",\"token\":\"{T-" + sequence[0] + "}\"," + + "\"token_expire_time\":\"" + beijing(clock) + "\"}," + + "\"errno\":0,\"err\":\"\",\"trace_id\":\"trace-" + sequence[0] + "\"}"); + }); + return new XincangAdapter(transport, new common.ecommerce.http.JacksonJsonCodec(), + tokens, locks, clock); + } + + /** 当前时钟 + 2 小时,按北京时间 {@code yyyy-MM-dd HH:mm:ss} 输出。 */ + private static String beijing(MutableClock clock) { + return java.time.LocalDateTime.ofInstant(clock.instant().plus(Duration.ofHours(2)), + XincangConstants.SYSTEM_ZONE) + .format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + } + + private static WarehouseContext ctx(String appKey) { + return WarehouseContext.of("XC-CA-3790", WarehouseProvider.XINCANG, "CA-3790", + WarehouseConnection.of(BASE, ChannelSecret.builder() + .appKey(appKey).appSecret("sk").build()), + "req-1", java.time.Clock.systemUTC()); + } + + private static int loginCount(RecordingTransport transport) { + int n = 0; + for (common.ecommerce.http.HttpRequest req : transport.recorded()) { + if (req.url().contains(XincangConstants.PATH_LOGIN)) { + n++; + } + } + return n; + } + + @Test + void secondLoginReusesCachedToken() { + XincangAdapter adapter = adapter(); + + String first = adapter.login(ctx(APP_KEY)).value(); + String second = adapter.login(ctx(APP_KEY)).value(); + + assertEquals(first, second); + assertEquals(1, loginCount(transport), "第二次登录必须命中缓存"); + assertEquals(1, locks.acquireCount("token-refresh:" + XincangConstants.ADAPTER_ID + ":" + APP_KEY)); + } + + @Test + void refreshesInsideEarlyWindow() { + XincangAdapter adapter = adapter(); + String first = adapter.login(ctx(APP_KEY)).value(); + + // 2h 有效期,提前 10 分钟续期:推进到 1h50m 后应重新登录 + clock.advance(Duration.ofMinutes(110)); + String second = adapter.login(ctx(APP_KEY)).value(); + + assertNotEquals(first, second, "进入提前续期窗口后必须换新 token"); + assertEquals(2, loginCount(transport)); + assertEquals(2, tokens.saveCount()); + } + + @Test + void tokenCacheIsPerAppKey() { + XincangAdapter adapter = adapter(); + + adapter.login(ctx("ak-1")); + adapter.login(ctx("ak-2")); + + assertEquals(2, loginCount(transport), "不同 appkey 各自登录"); + } + + @Test + void capabilitiesAreEmptyUntilBusinessApisLand() { + XincangAdapter adapter = adapter(); + + assertEquals(WarehouseProvider.XINCANG, adapter.provider()); + assertEquals(XincangConstants.ADAPTER_ID, adapter.adapterId()); + assertTrue(adapter.capabilities().isEmpty(), "本期只做登录,不声明任何能力位"); + assertFalse(adapter.supports("XC-CA-3790", WarehouseCapability.OUTBOUND)); + } +} diff --git a/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/auth/XincangTokenClientTest.java b/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/auth/XincangTokenClientTest.java new file mode 100644 index 0000000..e9482d3 --- /dev/null +++ b/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/auth/XincangTokenClientTest.java @@ -0,0 +1,153 @@ +package common.ecommerce.xincang.auth; + +import common.ecommerce.http.HttpRequest; +import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.shared.error.AuthException; +import common.ecommerce.shared.error.PlatformBusinessException; +import common.ecommerce.shared.error.ValidationException; +import common.ecommerce.shared.spi.AccessToken; +import common.ecommerce.shared.testkit.RecordingTransport; +import common.ecommerce.shared.testkit.Responses; +import common.ecommerce.xincang.XincangConstants; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * 信仓登录契约测试:请求形状、token / 过期时间解析、错误分类。 + * + *

请求与响应都按 Apifox「OMS接口文档V2」的真实报文构造,无需网络。

+ */ +class XincangTokenClientTest { + + private static final String BASE = "http://test.api.oms.13u3.com/oms"; + /** + * 测试用占位凭据。 + * + *

真实凭据(含文档里的测试 appkey/secret)一律不入库:联调用 + * {@code XincangLoginProbeTest} 走系统属性传入。

+ */ + private static final String APP_KEY = "test-appkey"; + private static final String APP_SECRET = "test-secret"; + private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-11-09T00:00:00Z"), ZoneOffset.UTC); + + /** 文档「成功示例」原文;token_expire_time 是北京时间。 */ + private static final String OK_BODY = "{" + + "\"rst\":{" + + "\"id\":\"120421451252766436\"," + + "\"api_client_id\":\"86159e50d22f31388b31ad135ff1174b\"," + + "\"api_client_secret\":\"RRWd7TeKJoMpoMvYZ0lpTkuYc7EgR4a0q18gE8Yn0cf03df7\"," + + "\"token_expire_time\":\"2026-10-14 09:34:09\"," + + "\"token\":\"{D0A7A4FB-6461-5EA4-194B-F273F1E87BFA}\"" + + "}," + + "\"errno\":0," + + "\"err\":\"\"," + + "\"trace_id\":\"005cbead-44f7-450d-9ed8-e1e65fbbb6e5\"" + + "}"; + + private static XincangTokenClient client(RecordingTransport transport) { + return new XincangTokenClient(transport, new JacksonJsonCodec(), CLOCK); + } + + @Test + void sendsGetWithCredentialsInQuery() { + RecordingTransport transport = RecordingTransport.create() + .route(XincangConstants.PATH_LOGIN, req -> Responses.ok(OK_BODY)); + + client(transport).fetch(BASE, APP_KEY, APP_SECRET); + + HttpRequest req = transport.recorded().get(0); + assertEquals("GET", req.method()); + assertTrue(req.url().startsWith(BASE + XincangConstants.PATH_LOGIN + "?"), req.url()); + assertTrue(req.url().contains("appkey=" + APP_KEY), req.url()); + assertTrue(req.url().contains("secret=" + APP_SECRET), req.url()); + // 信仓把 token 放 query,不发 Authorization 头 + assertFalse(req.headers().containsKey("Authorization"), req.headers().toString()); + } + + @Test + void parsesTokenAndBeijingExpiryToUtc() { + RecordingTransport transport = RecordingTransport.create() + .route(XincangConstants.PATH_LOGIN, req -> Responses.ok(OK_BODY)); + + AccessToken token = client(transport).fetch(BASE, APP_KEY, APP_SECRET); + + assertEquals("{D0A7A4FB-6461-5EA4-194B-F273F1E87BFA}", token.value()); + // 2026-10-14 09:34:09 北京时间 = 2026-10-14T01:34:09Z + assertEquals(Instant.parse("2026-10-14T01:34:09Z"), token.expiresAt()); + // 登录没有 refresh 机制 + assertNull(token.refreshToken()); + } + + @Test + void missingTokenFailsInsteadOfReturningBlank() { + RecordingTransport transport = RecordingTransport.create() + .route(XincangConstants.PATH_LOGIN, req -> Responses.ok( + "{\"rst\":{\"id\":\"1\",\"token_expire_time\":\"2026-10-14 09:34:09\"}," + + "\"errno\":0,\"err\":\"\",\"trace_id\":\"t-1\"}")); + + ValidationException e = assertThrows(ValidationException.class, + () -> client(transport).fetch(BASE, APP_KEY, APP_SECRET)); + assertTrue(e.getMessage().contains("rst.token"), e.getMessage()); + assertEquals("t-1", e.platformRequestId()); + } + + @Test + void malformedExpiryFailsInsteadOfGuessing() { + RecordingTransport transport = RecordingTransport.create() + .route(XincangConstants.PATH_LOGIN, req -> Responses.ok( + "{\"rst\":{\"token\":\"{T-1}\",\"token_expire_time\":\"2026/10/14 09:34\"}," + + "\"errno\":0,\"err\":\"\",\"trace_id\":\"t-2\"}")); + + ValidationException e = assertThrows(ValidationException.class, + () -> client(transport).fetch(BASE, APP_KEY, APP_SECRET)); + assertTrue(e.getMessage().contains("token_expire_time"), e.getMessage()); + } + + @Test + void missingExpiryFallsBackToDocumentedTwoHours() { + RecordingTransport transport = RecordingTransport.create() + .route(XincangConstants.PATH_LOGIN, req -> Responses.ok( + "{\"rst\":{\"token\":\"{T-2}\"},\"errno\":0,\"err\":\"\",\"trace_id\":\"t-3\"}")); + + AccessToken token = client(transport).fetch(BASE, APP_KEY, APP_SECRET); + + assertEquals(Instant.parse("2026-11-09T02:00:00Z"), token.expiresAt()); + } + + @Test + void nonzeroErrnoIsBusinessErrorWithTraceId() { + RecordingTransport transport = RecordingTransport.create() + .route(XincangConstants.PATH_LOGIN, req -> Responses.ok( + "{\"rst\":null,\"errno\":1001,\"err\":\"secret error\"," + + "\"trace_id\":\"t-4\"}")); + + PlatformBusinessException e = assertThrows(PlatformBusinessException.class, + () -> client(transport).fetch(BASE, APP_KEY, APP_SECRET)); + assertTrue(e.getMessage().contains("errno=1001"), e.getMessage()); + assertTrue(e.getMessage().contains("secret error"), e.getMessage()); + assertEquals("t-4", e.platformRequestId()); + assertEquals("1001", e.platformCode()); + } + + @Test + void http401IsAuthFailure() { + RecordingTransport transport = RecordingTransport.create() + .route(XincangConstants.PATH_LOGIN, req -> Responses.status(401, "")); + + assertThrows(AuthException.class, () -> client(transport).fetch(BASE, APP_KEY, APP_SECRET)); + } + + @Test + void blankCredentialsFailBeforeSending() { + RecordingTransport transport = RecordingTransport.create(); + + assertThrows(IllegalStateException.class, + () -> client(transport).fetch(BASE, " ", APP_SECRET)); + assertEquals(0, transport.recorded().size()); + } +} diff --git a/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/http/XincangRequestFactoryTest.java b/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/http/XincangRequestFactoryTest.java new file mode 100644 index 0000000..5754d02 --- /dev/null +++ b/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/http/XincangRequestFactoryTest.java @@ -0,0 +1,54 @@ +package common.ecommerce.xincang.http; + +import common.ecommerce.http.HttpRequest; +import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.xincang.XincangConstants; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * 信仓请求构造:token 放 query、基址末尾斜杠归一、缺 token 直接失败。 + */ +class XincangRequestFactoryTest { + + private static final String BASE = "http://test.api.oms.13u3.com/oms/"; + private final XincangRequestFactory factory = new XincangRequestFactory(new JacksonJsonCodec()); + + @Test + void loginPutsCredentialsInQuery() { + HttpRequest req = factory.login(BASE, "ak", "sk", "token.fetch"); + + assertEquals("GET", req.method()); + assertEquals("http://test.api.oms.13u3.com/oms" + XincangConstants.PATH_LOGIN + + "?appkey=ak&secret=sk", req.url()); + } + + @Test + void businessRequestCarriesTokenInQuery() { + Map params = new LinkedHashMap<>(); + params.put("page", 1); + params.put("limit", 20); + + HttpRequest req = factory.getWithToken(BASE, "/api.orderlist", params, "{T-1}", "outbound.query"); + + assertEquals("http://test.api.oms.13u3.com/oms/api.orderlist?page=1&limit=20&token=%7BT-1%7D", + req.url()); + assertFalse(req.headers().containsKey("Authorization")); + } + + @Test + void missingTokenFailsBeforeSending() { + assertThrows(IllegalStateException.class, + () -> factory.getWithToken(BASE, "/api.orderlist", null, " ", "outbound.query")); + } + + @Test + void missingAppKeyFailsBeforeSending() { + assertThrows(IllegalStateException.class, + () -> factory.login(BASE, "", "sk", "token.fetch")); + } +} diff --git a/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/probe/XincangLoginProbeTest.java b/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/probe/XincangLoginProbeTest.java new file mode 100644 index 0000000..b2625c3 --- /dev/null +++ b/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/probe/XincangLoginProbeTest.java @@ -0,0 +1,103 @@ +package common.ecommerce.xincang.probe; + +import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.http.OkHttpTransport; +import common.ecommerce.shared.error.ChannelException; +import common.ecommerce.shared.spi.AccessToken; +import common.ecommerce.shared.spi.ChannelSecret; +import common.ecommerce.shared.testkit.InMemoryLockProvider; +import common.ecommerce.shared.testkit.InMemoryTokenStore; +import common.ecommerce.warehouse.sdk.WarehouseConnection; +import common.ecommerce.warehouse.sdk.WarehouseContext; +import common.ecommerce.warehouse.WarehouseProvider; +import common.ecommerce.xincang.XincangConstants; +import common.ecommerce.xincang.adapter.XincangAdapter; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +import java.time.Clock; + +/** + * 信仓登录只读探针:核对 {@code GET /api.login} 的真实出入参。 + * + *

默认跳过,用 {@code -Dxincang.probe=true} 显式开启,凭据走系统属性、 + * 真实凭据不入库:

+ * + *
+ * mvn -pl warehouse-sdk-xincang -am -DfailIfNoTests=false \
+ *     -Dxincang.probe=true \
+ *     -Dxincang.probe.appKey=你的appkey -Dxincang.probe.appSecret=你的secret \
+ *     -Dtest=XincangLoginProbeTest test
+ * 
+ * + *

可选系统属性:{@code -Dxincang.probe.baseUrl}(默认测试环境 {@code XincangConstants.TEST_BASE_URL}) + * 与 {@code -Dxincang.probe.warehouseCode}(仅用于日志)。

+ * + *

只做登录,不调用任何业务接口;输出只打印 token 指纹与过期时间,不打印 token 本体。

+ */ +@EnabledIfSystemProperty(named = "xincang.probe", matches = "true") +class XincangLoginProbeTest { + + // 真实凭据不入库:本地跑探针时用 -Dxincang.probe.appKey=... -Dxincang.probe.appSecret=... + private static final String APP_KEY = System.getProperty("xincang.probe.appKey", ""); + private static final String APP_SECRET = System.getProperty("xincang.probe.appSecret", ""); + private static final String BASE_URL = opt("xincang.probe.baseUrl", XincangConstants.TEST_BASE_URL); + private static final String WAREHOUSE_CODE = opt("xincang.probe.warehouseCode", "XC-PROBE"); + + @Test + void probeLogin() { + Assumptions.assumeTrue(!APP_KEY.trim().isEmpty() && !APP_SECRET.trim().isEmpty(), + "未提供 -Dxincang.probe.appKey / -Dxincang.probe.appSecret,跳过登录探针"); + + System.out.println("\n================ xincang / api.login ================"); + System.out.println("[login] baseUrl=" + BASE_URL + " appKey=" + mask()); + + XincangAdapter adapter = new XincangAdapter( + new OkHttpTransport("common-ecommerce-xincang-probe"), + new JacksonJsonCodec(), + new InMemoryTokenStore(), new InMemoryLockProvider(), Clock.systemUTC()); + WarehouseContext ctx = WarehouseContext.of(WAREHOUSE_CODE, WarehouseProvider.XINCANG, null, + WarehouseConnection.of(BASE_URL, ChannelSecret.builder() + .appKey(APP_KEY).appSecret(APP_SECRET).build()), + "probe-" + System.currentTimeMillis(), Clock.systemUTC()); + + try { + AccessToken token = adapter.login(ctx); + System.out.println("[login] ok token=" + token.fingerprint() + + " expiresAt=" + token.expiresAt() + + " (剩余 " + seconds(token) + " 秒)"); + } catch (RuntimeException e) { + // 探针异常只打印不抛出,方便一次跑完并对照真实报文 + String msg = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); + System.out.println("[ERROR] " + e.getClass().getSimpleName() + ": " + + (msg.length() <= 300 ? msg : msg.substring(0, 300) + "…")); + if (e instanceof ChannelException) { + ChannelException ce = (ChannelException) e; + System.out.println(" platformCode=" + ce.platformCode() + + " platformRequestId=" + ce.platformRequestId() + + " retryable=" + ce.retryable()); + } + } + } + + private static long seconds(AccessToken token) { + return token.expiresAt().getEpochSecond() - java.time.Instant.now().getEpochSecond(); + } + + private static String mask() { + if (XincangLoginProbeTest.APP_KEY.length() <= 6) { + return "***"; + } + return XincangLoginProbeTest.APP_KEY.substring(0, 4) + "***" + XincangLoginProbeTest.APP_KEY.substring(XincangLoginProbeTest.APP_KEY.length() - 2); + } + + private static String opt(String name, String fallback) { + String value = System.getProperty(name, ""); + if (value == null) { + return fallback; + } + String trimmed = value.trim(); + return trimmed.isEmpty() ? fallback : trimmed; + } +}